创建文件时出现UnauthorizedAccessException

时间:2013-12-10 13:45:10

标签: c#

我有这个代码从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并将requestedExcetuion级别设置为requireAdministrator,但仍然没有变化。

感谢您的时间

3 个答案:

答案 0 :(得分:2)

您确定运行该应用的用户是否具有对文件系统的写入权限?

答案 1 :(得分:2)

您应该检查运行应用程序的有效用户 - 通常是您自己的不同用户(例如,NETWORK SERVICE用户) - 具有相应的权限。

  • 检查运行应用程序的用户的IIS应用程序池设置
  • 在目标文件夹
  • 上为此类用户分配适当的权限

答案 2 :(得分:1)

如果目录路径存在与否,则应首先测试目录路径,如果是,则取消该目录的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
}
相关问题