在C#中创建文本文件

6
我是一名有用的助手,可以为您进行文字翻译。以下是需要翻译的内容:

我正在学习如何在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)”。问题出在哪里?

4
C:\CSharpTestFolder 存在吗?如果创建它,你的代码能够运行吗?你是否有适当的权限来编辑该文件夹? - Liath
不,这个文件不存在。当我手动创建了这个路径并再次运行程序时,它显示相同的错误,但是该路径中的“test.txt”文件是由程序生成的,但是当我打开它时,里面没有文本。我不确定,但我认为它有编辑权限。 - TheZerda
4个回答

12

假设你所说的目录存在(如你所言),那么你有另一个问题。

File.Create 创建的文件会保持锁定状态,因此你不能以这种方式使用 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");

7
这个异常表明您的目录C:\CSharpTestFolder不存在。File.Create会在现有的文件夹/路径中创建一个文件,但不会创建整个路径。

由于目录和文件都不存在,所以您的检查File.Exists(path)将返回false。您需要首先在文件夹上检查Directory.Exists,然后创建您的目录和文件。

将文件操作放在try/catch中。您无法百分之百确定File.ExistsDirectory.Exists,因为可能会有其他进程创建/删除这些项目,并且如果完全依赖这些检查,可能会遇到问题。

您可以像这样创建目录:

string directoryName = Path.GetDirectoryName(path);
Directory.CreateDirectory(directoryName);

(如果文件夹已经存在,调用Directory.CreateDirectory时不需要调用Directory.Exists,它不会抛出异常)然后检查/创建您的文件


1
请参考此答案,了解如何创建目录 https://dev59.com/r3A75IYBdhLWcg3wm6ax。同时也可以创建所需的文件夹。 - Liath

6

您需要先创建目录。

string directory = @"C:\CSharpTestFolder";

if(!Directory.Exists(directory))
    Directory.CreateDirectory(directory);

string path = Path.Combine(directory, "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);

1
尝试一下。
string path = @"C:\CSharpTestFolder";

if (Directory.Exists(path))
{
    File.AppendAllText(path + "\\Test.txt", "The first line");
}

else
{
    Directory.CreateDirectory(path);
    File.AppendAllText(path + "\\Test.txt", "The first line");
}
File.AppendAllText(path, text) 方法将在文件不存在时创建一个文本文件;将文本追加到文件中,然后关闭文件。 如果文件已经存在,它将打开文件并将文本追加到文件中,然后关闭文件。
异常显示目录 C:\CSharpTestFolder 不存在。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接