簡體   English   中英

ASP.NET MVC網站從磁盤問題中讀取文件

[英]ASP.NET MVC Website Read File from Disk Problem

我正在使用C#在我正在研究的MVC網站上讀取包含SQL插入語句的文本文件。 調試我正在使用的函數工作正常,插入發生。 但是,一旦我發布該網站並在我的本地計算機上運行它(使用IIS設置甚至使用asp.net 4.0)它似乎不起作用。

        if (Request.Files != null && Request.Files["txtImportFile"] != null)
        {
            //newFilePath = Server.MapPath("\\" + DateTime.Now.Ticks + Request.Files["txtImportFile"].FileName);
            string[] temp_string = Request.Files["txtImportFile"].FileName.Split(new char[] { '\\' });
            string temp_filename = temp_string[temp_string.Count() - 1];
            //newFilePath = Server.MapPath("\\temp\\" + DateTime.Now.Ticks + Request.Files["txtImportFile"].FileName);
            newFilePath = Server.MapPath("\\temp\\" + DateTime.Now.Ticks + temp_filename);
            Request.Files["txtImportFile"].SaveAs(newFilePath);

            StreamReader reader = new StreamReader(newFilePath);
            string contents = reader.ReadToEnd();
            reader.Close();

            Models.WingsRemoteDbLibrary dbLib = new Models.WingsRemoteDbLibrary();
            string update_message = dbLib.UpdateSlaveItemsTable(contents);

            if (System.IO.File.Exists(newFilePath))
                System.IO.File.Delete(newFilePath);

            RandomPopupView(update_message);
        }

我希望我的解釋聽起來不含糊。 我會盡力回答任何進一步的問題。 謝謝。

解決方法:

而不是使用

Server.MapPath("\\temp\\"...

在root下創建名為“temp”的文件夾並使用

System.Web.HttpContext.Current.Request.MapPath("~\\temp....

嗯,“它似乎不起作用”是非常模糊的 - 更多細節會很好! 但這聽起來像是權限問題。 IIS中的默認配置文件幾乎無法訪問磁盤, 尤其是寫訪問。 無論如何在自己的網站內部編寫並不是一個好主意(我自己使用磁盤中不相關的部分),但是您需要配置IIS以在特定的命名身份中運行應用程序,並且可以訪問磁盤。 不幸的是,配置帳戶本身 (不是IIS - 帳戶;例如授予“作為服務登錄”)作為ASP.NET帳戶運行並不是特別微不足道。

另一個想法:你的應用程序是一個子應用程序,即你的app-root / ,還是它/MyApp/ 我問的原因是你對MapPath的使用可能相對於app-root更好地表達,即~/temp/ - 但我再次強調; 在應用程序內部寫作是有風險的。 真的希望該文件夾不執行。

這個問題可能有另一種解決方案。 如果您可以在構建時將文件“烘焙”到程序集中,則可以完全避免弄亂路徑和文件系統。 以下是如何執行此操作的方法:

  1. 在Visual Studio解決方案資源管理器中,右鍵單擊文件並轉到“屬性”。

  2. 將Build Action設置為“Embedded Resource”。

  3. 稍后您可以使用GetManifestResourceStream讀取該文件:

      var stream = GetType() .Assembly .GetManifestResourceStream("YourNameSpace.Folder.YourFile.txt"); using (var reader = new StreamReader(stream)) { var fileContent = reader.ReadToEnd(); } 

    更多信息在這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM