c# - 访问文件系统 Azure 应用服务

标签 c# azure azure-web-app-service

我有一个 Azure 应用程序 (.Net 4.5),并且文件系统上存储了一些我想要读取的静态文件,但我收到一个 System.UnauthorizedAccessException ,如下所示

string template = string.Empty;
var file = HostingEnvironment.MapPath("~/App_Data/EmailTemplates/" + fileName);
if (!string.IsNullOrEmpty(file))
     {
        template = File.ReadAllText(file); <-- Unauthorized Access Exception Here
     }
return template;

我知道最佳实践是 Azure 存储,但我如何才能做到这一点?

最佳答案

File.ReadAllText状态关于 UnauthorizedAccessException ,可能是由以下情况之一引起的:

  • path specified a file that is read-only.

-or-

  • This operation is not supported on the current platform.

-or-

  • path specified a directory.

-or-

  • The caller does not have the required permission.

您可以利用 kudu 控制台并使用 Attrib命令检查文件或目录的属性。另外,您可以尝试使用 TYPE命令显示文件的内容或单击文件列表中的“编辑”按钮,如下所示:

enter image description here

另外,我创建了一个新的Web应用程序并部署了MVC应用程序来显示App_Data文件夹下的文件,它可以按预期工作,您可以引用it .

更新:

//method for getting files
public List<DownLoadFileInformation> GetFiles()
{
    List<DownLoadFileInformation> lstFiles = new List<DownLoadFileInformation>();
    DirectoryInfo dirInfo = new DirectoryInfo(HostingEnvironment.MapPath("~/App_Data"));

    int i = 0;
    foreach (var item in dirInfo.GetFiles())
    {
        lstFiles.Add(new DownLoadFileInformation()
        {

            FileId = i + 1,
            FileName = item.Name,
            FilePath = dirInfo.FullName + @"\" + item.Name
        });
        i = i + 1;
    }
    return lstFiles;
}

//action for downloading a file
public ActionResult Download(string FileID)
{
    int CurrentFileID = Convert.ToInt32(FileID);
    var filesCol = obj.GetFiles();
    string fullFilePath = (from fls in filesCol
                                where fls.FileId == CurrentFileID
                                select fls.FilePath).First();

    string contentType = MimeMapping.GetMimeMapping(fullFilePath);
    return File(fullFilePath, contentType, new FileInfo(fullFilePath).Name);
}

更新2:

public ActionResult ViewOnline(string FileID)
{
    int CurrentFileID = Convert.ToInt32(FileID);
    var filesCol = obj.GetFiles();
    string fullFilePath = (from fls in filesCol
                                where fls.FileId == CurrentFileID
                                select fls.FilePath).First();
    string text = System.IO.File.ReadAllText(fullFilePath);
    return Content(text);
}

关于c# - 访问文件系统 Azure 应用服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45447746/

相关文章:

c# - c# 中的 DateTime 和 SQL Server 中的 DateTime 之间有什么区别吗?

azure - 当前映射子网创建中的 CIDR 值错误

azure - 如何在 NewRelic 中跟踪 Azure Web 应用程序的部署?

c# - 使用创建的扩展方法

c# - SharpDevelop 中断点上的橄榄色子弹意味着什么

c# - 无法使用带有汉字 Json 数据的 Azure Active Directory B2C Graph API 创建新用户

Azure Web App - 将具有自定义域的生产槽备份恢复到部署槽

c# - 使用自定义模型通过 C# 中的 Forms Recognizer V3 nuget 从表中提取数据

asp.net - azure 网站不会从基本网站缩小,因为报告的大小不正确

c# - 在 rtf 字符串的位置追加文本