Dot-Net

將數據寫入 App_Data

  • April 18, 2021

我想使用以下程式碼將 .xml 文件寫入 App_Data/posts。為什麼會導致錯誤?

程式碼

Stream writer  = new FileStream("..'\'App_Data'\'posts'\'" + new Guid(post_ID.ToString()).ToString() + ".xml", FileMode.Create);

請發布您得到的異常;不僅僅是“它不起作用”——這可能是各種各樣的問題。這裡有幾件事要檢查:

檢查 ASP.NET 程序是否對該目錄具有寫入權限。

此外,您似乎在錯誤地轉義路徑中的退格鍵。在使用 ASP.NET 時,您的路徑應該是相對於應用程序根目錄的。嘗試這個:

string path = HttpContext.Current.Server.MapPath("~/App_Data/posts/" + new Guid(post_ID.ToString()).ToString() + ".xml"
Stream writer  = new FileStream(path, FileMode.Create);

最後,確保文章目錄存在 - 否則文件創建將失敗。

引用自:https://stackoverflow.com/questions/2574587