我有一个 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命令显示文件的内容或单击文件列表中的“编辑”按钮,如下所示:
另外,我创建了一个新的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/