Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Visual C#在桌面上创建文本文件访问被拒绝_C# - Fatal编程技术网

Visual C#在桌面上创建文本文件访问被拒绝

Visual C#在桌面上创建文本文件访问被拒绝,c#,C#,加载表单时的我的代码: string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); if (!File.Exists(path)) { // Create a file to write to. using (StreamWriter sw = File.CreateText(path)) { sw.WriteLine("test"); } } 这就是

加载表单时的我的代码:

string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (!File.Exists(path))
{
    // Create a file to write to. 
    using (StreamWriter sw = File.CreateText(path))
    {
        sw.WriteLine("test");
    }

}

这就是我经常遇到的错误:

您的代码现在正在尝试创建一个与桌面文件夹同名的文件。要创建新文件,需要在路径字符串的末尾追加文件名。试着这样做:

string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (!File.Exists(path + @"\test.txt"))
{
    // Create a file to write to.
    using (StreamWriter streamWriter = File.CreateText(path + @"\test.txt"))
    {
        streamWriter.WriteLine("test");
    }
}

字符串中的
@
符号使编译器忽略字符串中的任何转义字符,将其视为字符串文字。此代码将检查桌面上是否存在名为test.txt的文件。如果没有,它将创建一个并向其中写入“test”。

那么您正试图创建一个与桌面文件夹同名的文件?“不行……我正试图在桌面上创建一个新的文本文件,我不知道我在做什么。”@urbexpxuc看看Lokisinlair链接的问题。解决方案就在那里,只要看看答案。只需使用路径。而不是组合