简体   繁体   English

UnauthorizedAccessException C#

[英]UnauthorizedAccessException c#

Im getting an UnauthorizedAccessException when I try to write files to a newly created folder. 我在尝试将文件写入新创建的文件夹时收到UnauthorizedAccessException It should create a writable folder. 它应该创建一个可写文件夹。

Here is the code I am using: 这是我正在使用的代码:

 //creating folder
uploadDirectory = directoryBox.Text + "\\Uploads";
 if (!Directory.Exists(uploadDirectory))
    {
       Directory.CreateDirectory(uploadDirectory);
    }
//writing file to folder
File.WriteAllBytes(uploadDirectory, file);

The file is a bytefile. 该文件是一个字节文件。 How can I make the folder writable? 如何使文件夹可写?

You are attempting to write to the upload directory. 您正在尝试写入上载目录。 You should be writing to a file. 您应该正在写入文件。 So really your code should be 所以实际上您的代码应该是

File.WriteAllBytes(uploadDirectory + "\\" + fileName, file)

You might also have to add permissions to the folder. 您可能还必须向该文件夹添加权限。

        DirectoryInfo directoryInfo = new DirectoryInfo(uploadDirectory);
        if (!directoryInfo.Exists)
        {
            Directory.CreateDirectory(uploadDirectory);
        }

        var sec = directoryInfo.GetAccessControl();
        var accessRule = new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow);

        sec.AddAccessRule(accessRule);
        directoryInfo.SetAccessControl(sec);

This should be done before attempting to write to the file. 这应该在尝试写入文件之前完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM