2017-08-01 78 views
0

我有一個Azure的應用程序(.NET 4.5),我有存儲在文件系統中的一些靜態文件,我想從閱讀,但我得到一個System.UnauthorizedAccessException的像這樣訪問文件系統Azure的應用服務

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存儲,但我如何以這種方式進行此項工作?

+2

什麼是在MapPath()路徑最終會被?您可以完全訪問'd:\ home \ site \ wwwroot'。 (注意:只要你不刪除你的網絡應用程序,'site'下的存儲是持久的,就像Azure存儲一樣)。 –

+0

地圖路徑給了我正確的位置(至少在Kudu看),但它說無效訪問 –

+1

您能否請編輯您的問題與更多的細節,包括完整的錯誤,以及哪些調用產生的錯誤? (我假設'ReadAllText()',但不知道肯定)。 –

回答

2

由於File.ReadAllText州約UnauthorizedAccessException,它可以由以下條件之一引起:

  • 路徑指定了一個只讀文件。

- 或 -

  • 此操作不支持當前平臺上。

- 或 -

  • 路徑指定的目錄中。

- 或 -

  • 調用方沒有所要求的權限。

你可以利用捻控制檯和使用Attrib命令檢查屬性爲您的文件或目錄。此外,您可以嘗試使用TYPE命令顯示文件的內容或從文件目錄表單擊編輯按鈕,如下所示:

enter image description here

而且,我創建了一個新的Web應用程序,並部署了我MVC應用程序顯示App_Data文件夾下的文件,它可以按預期工作,您可以參考it

UPDATE:

//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); 
} 

UPDATE2:

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); 
} 
+0

唯一真正的區別是,我是從API而不是MVC做到這一點,你能告訴我片段讀取文件的內容? –

+0

我用相關的代碼片段更新了我的答案。我也檢查使用'File.ReadAllText'來檢索我的json文件的內容。 –

+0

謝謝,所以你實際上並沒有打開Code後面的文件? –