简体   繁体   English

c#拒绝访问路径?

[英]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: 和getTemporaryDirectory方法:

 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. dir = C:\\ Users \\ Jack Givens \\ AppData \\ Local \\ Temp \\ 5ftxwy31.txt mscorlib.dll中出现'System.UnauthorizedAccessException'类型的第一次机会异常mscorlib.dll中发生未处理的类型'System.UnauthorizedAccessException'异常附加信息:拒绝访问路径'C:\\ Users \\ Jack Givens \\ AppData \\ Local \\ Temp \\ 0lpe1k5t.txt'。

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". 您刚刚创建了一个目录,其名称以“* .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. 您在文件名上调用CreateDirectory ,因此现在File.Create尝试调用的路径中存在一个文件夹。 Just simply remove the Directory.CreateDirectory(tempFile); 只需删除Directory.CreateDirectory(tempFile); line (it is not needed as the folder is guaranteed to exist) and your code should work. line(不需要它,因为文件夹保证存在)并且您的代码应该可以工作。

You are creating a directory, not a file. 您正在创建目录,而不是文件。 You can't open a directory as a file. 您无法将目录作为文件打开。

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

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