“ 'System.UnauthorizedAccessException' occ

2019-09-07 03:42发布

I'm doing this project where I grab some information and save it to a file. While trying to create that file, I always get an System.UnauthorizedAccesssException error. I've tried adding a manifest file and requiring admin, still doesn't work. I've also released it and ran the program through the \bin folder, and it still didn't work.

Here is my code:

public static void CreateFile(string path, string name)
{
    Debug.WriteLine("Starting to create file...");
    string Name = name;
    string path2 = path;
    string fullPath = Path.Combine(path2, Name);
    using (FileStream fs = new FileStream(fullPath, FileMode.Create))
    {
        Debug.WriteLine("File Created");
    }
}

I also tried going to the Microsoft website and using their method of creating a file, and it still didn't work, I got the same error!

Question is, how I give access to the program in order to write to the C:\ drive?

1条回答
霸刀☆藐视天下
2楼-- · 2019-09-07 04:14

By default most user accounts lack the necessary access to write directly to the C:\ drive. The exception, UnauthorizedAccessException, indicates that this is the case here.

To make this work you're going to need to either

  1. Pick a more standard location to write the file
  2. Give the account under which this program runs access to the C:\ drive.

Of the two #1 is by far the more preferable option

查看更多
登录 后发表回答