带有ASP.Net Core和Razor页面的Azure存储FileShare [英] Azure Storage FileShare with ASP.Net Core and Razor Page

查看:107
本文介绍了带有ASP.Net Core和Razor页面的Azure存储FileShare的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

初学者问题

我正在使用最新的ASP.NET Core SDK来构建MVC/Razor页面以显示用户文件.我们在Azure存储FileShare中有文件.我遇到的困难是要列出文件,并且关于如何执行此操作的文档很少.一旦我终于弄清楚了,我想在Medium或其他地方创建一个帖子,以帮助任何其他初学者.

I am using the latest ASP.NET Core SDK to build an MVC/Razor page to display user files. We have the files in Azure Storage FileShare. The difficulty I'm running into is getting the FILES to list out and there is very little documentation on how to do this out there. Once I finally get it figured out I would like to create a post on Medium or somewhere else to help any other beginners.

文件共享的文件结构如下:

The file structure of the File Share is as such:

Azure File Share
  MainShare
    EmployeNumber
      Folder1
        files.pdf
      Folder2
        files.pdf
      Folder3
        files.pdf

我能够成功获取要显示的Blob信息,因为那里有大量信息,但是FileShare无法显示任何内容.

I have been able to successfully get blob information to display since that's the bulk of information out there, but I'm having trouble FileShare to display anything.

起初,我遇到一个无效的强制转换问题,它试图将 CloudFileDirectory 强制转换到我的 CloudFile 上,因此我找到了一个解决方案来帮助其确定要强制转换的内容在哪里.现在,该页面将尝试运行,但不会产生任何结果,并且页面只会加载和加载.

At first, I was running into an invalid cast issue where it was trying to cast CloudFileDirectory on my CloudFile so I found a solution to help it determine what to cast where. Now the page will attempt to run but nothing is produced and the page just loads and loads.

FileController.cs

public async Task<IActionResult> Index()
        {
            string filestorageconnection = _configuration.GetValue<string>("filestorage");
            CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(filestorageconnection);

            //CloudFile cloudFile = null;
            
            CloudFileShare fileShare = null;

            CloudFileClient cloudFileClient = cloudStorageAccount.CreateCloudFileClient();

            fileShare = cloudFileClient.GetShareReference("MainShare");
            

            List<IListFileItem> shareData = new List<IListFileItem>();
            List<FileShareData> fileData = new List<FileShareData>();

            FileContinuationToken token = null;
            do
            {
                FileResultSegment resultSegment =
                    await fileShare.GetRootDirectoryReference().ListFilesAndDirectoriesSegmentedAsync(token);

                foreach (var fileItem in resultSegment.Results)
                {
                    if (fileItem is CloudFile)
                    {
                        var cloudFile = (CloudFile) fileItem;
                        //await cloudFile.FetchAttributesAsync();   <--- Not sure this does what i'm looking for
                        
                        // Add properties to FileShareData List
                        fileData.Add(new FileShareData()
                        {
                            FileName = cloudFile.Name,
                            LastModified = DateTime.Parse(cloudFile.Properties.LastModified.ToString()).ToLocalTime().ToString(),
                            Size = Math.Round((cloudFile.Properties.Length / 1024f) / 1024f, 2).ToString()
                        });
                    }
                    else if (fileItem is CloudFileDirectory)
                    {
                        var cloudFileDirectory = (CloudFileDirectory) fileItem;
                        await cloudFileDirectory.FetchAttributesAsync();
                    }
                }
            } while (token != null);

            return View(fileData);  
        }

FileShareData.cs

namespace FileShareMVC.Models
{
    public class FileShareData
    {
        public string FileName { get; set; }
        public string LastModified { get; set; }
        public string Size { get; set; }
    }
}

ShowAllFiles.cshtml

@model List<FileShareData>
@{
    ViewData["Title"] = "ShowAllFiles";
}

<h1>ShowAllBlobs</h1>
<table class="table table-bordered">
    <thead>
    <tr>
        <th>FileName</th>
        <th>FileSize</th>
        <th>ModifiedOn</th>
        <th>Download</th>
    </tr>
    </thead>
    <tbody>
    @foreach (var data in Model)
    {
        <tr>
            <td>@data.FileName</td>
            <td>@data.Size</td>
            <td>@data.LastModified</td>
            <td> <a href="/File/Download?fileName=@data.FileName">Download</a> </td>
        </tr>
    }
    </tbody>
</table>

我不确定在哪里设置断点以查看停滞在什么地方.加载页面时,我查看了Chrome中的网络文件,但也没有填充.

I'm not sure where to set a breakpoint to see whats stalling where. I've looked at the Network files in chrome when loading the page but nothing populates either.

建议?

推荐答案

关于如何使用方法 ListFilesAndDirectoriesSegmentedAsync 在一个Azure文件共享中列出所有文件,请参考以下代码

Regarding how to list all files in one Azure file share with method ListFilesAndDirectoriesSegmentedAsync, please refer to the following code

文件共享的文件结构如下:

The file structure of the File Share is as such:

Azure File Share
  MainShare
     mydirectory
      logs
        STATS.LOG        
      csv
        test.csv
      cert
        examplecert.pfx

我使用的SDK

<PackageReference Include="Microsoft.Azure.Storage.File" Version="11.1.7" />

代码

  • FileController.cs
public class FileController : Controller
    {
        public async Task<IActionResult> Index()
        {
            string accountName = "blobstorage0516";
            string key = "eGier5YJBzr5z3xgOJUb+snTGDKhwPBJRFqb2nL5lcacmKZXHgY+LjmYapIHL7Csvgx75NwiOZE7kYLJfLqWBg==";
            var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, key), true);
            var share = storageAccount.CreateCloudFileClient().GetShareReference("mainshare");
            var dir =share.GetRootDirectoryReference();
            //list all files in the directory
            var fileData = await list_subdir(dir);
            return View(fileData);
        }



        private static async Task<List<FileShareData>> list_subdir(CloudFileDirectory fileDirectory)
        {
            var fileData = new List<FileShareData>();
            FileContinuationToken token = null;
            do
            {
                FileResultSegment resultSegment = await fileDirectory.ListFilesAndDirectoriesSegmentedAsync(token);
                foreach (var fileItem in resultSegment.Results) {

                    if (fileItem is CloudFile) {
                        var cloudFile = (CloudFile)fileItem;
                        //get the cloudfile's propertities and metadata 
                        await cloudFile.FetchAttributesAsync();  

                        // Add properties to FileShareData List
                        fileData.Add(new FileShareData()
                        {
                            FileName = cloudFile.Name,
                            LastModified = DateTime.Parse(cloudFile.Properties.LastModified.ToString()).ToLocalTime().ToString(),
                            // get file size as kb
                            Size = Math.Round((cloudFile.Properties.Length / 1024f), 2).ToString()
                        });

                    }

                    if (fileItem is CloudFileDirectory)
                    {
                        var cloudFileDirectory = (CloudFileDirectory)fileItem;
                        await cloudFileDirectory.FetchAttributesAsync();

                        //list files in the directory
                        var result = await list_subdir(cloudFileDirectory);
                        fileData.AddRange(result);
                    }
                }
                // get the FileContinuationToken to check if we need to stop the loop
                token = resultSegment.ContinuationToken;
            }
            while (token != null);

            return fileData;
            

        }
    }

  • FileShareData.cs
  • public class FileShareData
        {
            public string FileName { get; set; }
            public string LastModified { get; set; }
            public string Size { get; set; }
        }
    

    • ShowAllFiles.cshtml
    • @model List<FileShareData>
      @{
          ViewData["Title"] = "ShowAllFiles";
      }
      
      <h1>ShowAllBlobs</h1>
      <table class="table table-bordered">
          <thead>
          <tr>
              <th>FileName</th>
              <th>FileSize</th>
              <th>ModifiedOn</th>
              <th>Download</th>
          </tr>
          </thead>
          <tbody>
          @foreach (var data in Model)
          {
              <tr>
                  <td>@data.FileName</td>
                  <td>@data.Size</td>
                  <td>@data.LastModified</td>
                  <td> <a href="/File/Download?fileName=@data.FileName">Download</a> </td>
              </tr>
          }
          </tbody>
      </table>
      

      结果

      有关更多详细信息,请参考此处此处

      For more details, please refer to here and here

      这篇关于带有ASP.Net Core和Razor页面的Azure存储FileShare的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆