在 C# 中创建文本文件

2023-11-27

我正在学习如何在 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);

}

当我按下“创建”按钮时,Visual Studio 显示错误“System.IO.DirectoryNotFoundException”,该错误指向“File.Create(path)”。

哪里有问题?


好吧,假设你的目录存在(正如你所说)那么你还有另一个问题

文件.创建保持锁定它创建的文件,您不能以这种方式使用 StreamWriter。

相反,你需要写

using(FileStream strm = File.Create(path))
using(StreamWriter sw = new StreamWriter(strm))
    sw.WriteLine("The first line!");

然而,这一切并不是真正必要的,除非您需要使用特定选项创建文件(请参阅 File.Create 重载列表) 因为如果文件不存在,StreamWriter 会自行创建该文件。

// File.Create(path);
using(StreamWriter sw = new StreamWriter(path))
    sw.WriteLine("Text");

...或全部在一条线上

File.WriteAllText(path, "The first line");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 C# 中创建文本文件 的相关文章

随机推荐