簡體   English   中英

創建文件時出現UnauthorizedAccessException

[英]UnauthorizedAccessException when Creating file

我有這段代碼,該代碼從ftp服務器下載文件,然后在設置的路徑中創建該文件。

  string inputfilepath = @"C:\Users\me\Documents\Test";
        string ftphost = "ftp_server";
        string ftpfilepath = @"/TestDOTNET/text.TXT";

        string ftpfullpath = "ftp://" + ftphost + ftpfilepath;

        using (WebClient request = new WebClient())
        {
            request.Proxy = null;
            request.Credentials = new NetworkCredential("user", "pass");
            byte[] fileData = request.DownloadData(ftpfullpath);

            File.SetAttributes(inputfilepath, FileAttributes.Normal);  

            using (FileStream file = File.Create(inputfilepath)) // this is the line where I get the exception
            {
                file.Write(fileData, 0, fileData.Length);
                file.Close();
            }
            MessageBox.Show("Download Complete");

        }

我試圖創建app.manifest並將requireAdministrator級別設置為requireAdministrator但仍然沒有任何變化。

感謝您的時間

您確定運行該應用程序的用戶具有對文件系統的寫訪問權嗎?

您應該檢查運行該應用程序的有效用戶(通常是您自己的用戶(例如,NETWORK SERVICE用戶))是否具有適當的權限。

  • 檢查IIS應用程序池設置,即運行該應用程序的用戶
  • 在目標文件夾上為該用戶分配適當的權限

您應該首先測試目錄路徑是否存在(如果存在),然后否定該目錄的read-only屬性。 如果不是,則創建目錄,然后創建test.txt以寫入其中。 防爆::

string inputdirpath = @"C:\Users\me\Documents\Test";
string inputfilepath = inputdirpath + "\text.TXT";

 // Downloading Stuff
 if(Directory.Exists(inputdirpath )) 
 {
    var di = new DirectoryInfo("inputfilepath "); 
    di.Attributes &= ~FileAttributes.ReadOnly;

    using (FileStream file = File.Create(inputfilepath)) 
            {
                file.Write(fileData, 0, fileData.Length);
                file.Close();
            }
            MessageBox.Show("Download Complete");
 }
else
{
  // Create Directory
  // Set Attributes
  // Create file
  // Write data
}

暫無
暫無

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

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