简体   繁体   中英

c# Access to path denied?

I'm having trouble with an error. I have searched the web but havent found an answer that made sense to me. I'm basically trying to create a temporary text file, and write to it. Here it the code concerning the error:

using ( StreamWriter output = new StreamWriter(File.Create(GetTemporaryDirectory())))

and the getTemporaryDirectory method:

 public string GetTemporaryDirectory() {
        string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
        string tempFile = Path.ChangeExtension(tempDirectory, ".txt");
        Directory.CreateDirectory(tempFile);
        return tempFile;
    }

and last but not least the error:

dir = C:\\Users\\Jack Givens\\AppData\\Local\\Temp\\5ftxwy31.txt A first chance exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll An unhandled exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll Additional information: Access to the path 'C:\\Users\\Jack Givens\\AppData\\Local\\Temp\\0lpe1k5t.txt' is denied.

If anyone can tell me what is wrong with my code and what i need to do to fix it, I will appreciate it. side note: sorry for crappy code, i'm kinda a beginner :)

 Directory.CreateDirectory(tempFile);

You have just created a directory, the name of which ends in "*.txt".

Then you attempt to create a file with the exact same path. But that's not possible.

You call CreateDirectory on your filename so now a folder exists in the path that File.Create is attempting to call. Just simply remove the Directory.CreateDirectory(tempFile); line (it is not needed as the folder is guaranteed to exist) and your code should work.

You are creating a directory, not a file. You can't open a directory as a file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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