小编The*_*rda的帖子

在C#中创建文本文件

我正在学习如何在C#中创建文本文件,但我遇到了问题.我用过这段代码:

private void btnCreate_Click(object sender, EventArgs e)        
{

    string path = @"C:\CSharpTestFolder\Test.txt";
    if (!File.Exists(path))
    {
        File.Create(path);
        using (StreamWriter sw = File.CreateText(path))
        {
            sw.WriteLine("The first line!");
        }

    }
    else if (File.Exists(path))
        MessageBox.Show("File with this path already exists.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);

}
Run Code Online (Sandbox Code Playgroud)

当我按下"创建"按钮时,Visual Studio会显示错误"System.IO.DirectoryNotFoundException",它指向"File.Create(path)".

问题出在哪儿?

c# file path streamwriter

2
推荐指数
3
解决办法
8120
查看次数

标签 统计

c# ×1

file ×1

path ×1

streamwriter ×1