“ 'System.UnauthorizedAccessException' occurred in mscorlib.dll” while trying to create file in the C:\ drive

我是研究僧i 提交于 2019-12-11 14:18:04

问题


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:


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



来源:https://stackoverflow.com/questions/20928736/system-unauthorizedaccessexception-occurred-in-mscorlib-dll-while-trying-to

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!