在C#中创建文本文件

The*_*rda 2 c# file path streamwriter

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

问题出在哪儿?

Hab*_*bib 7

例外情况表明您的目录C:\CSharpTestFolder不存在.File.Create将在现有文件夹/路径中创建一个文件,它也不会创建完整路径.

您的检查File.Exists(path)将返回false,因为该目录不存在,因此文件也是如此.您需要先检查Directory.Exists文件夹,然后创建目录,然后再创建文件.

将您的文件操作包含在内try/catch.您无法100%确定,File.Exists并且Directory.Exists可能有其他流程创建/删除项目,如果您完全依赖这些检查,则可能会遇到问题.

您可以创建目录,如:

string directoryName = Path.GetDirectoryName(path);
Directory.CreateDirectory(directoryName);
Run Code Online (Sandbox Code Playgroud)

(您可以在Directory.CreateDirectory不调用的情况下调用Directory.Exists,如果该文件夹已存在则不会抛出异常),然后检查/创建您的文件


Ste*_*eve 7

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

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

相反,你需要写

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

但是,除非您需要使用特定选项创建文件(请参阅File.Create重载列表),否则所有这些都不是必需的,因为如果文件不存在,StreamWriter会自行创建文件.

// File.Create(path);
using(StreamWriter sw = new StreamWriter(path))
    sw.WriteLine("Text");
Run Code Online (Sandbox Code Playgroud)

......或全部在一条线上

File.WriteAllText(path, "The first line");
Run Code Online (Sandbox Code Playgroud)


Jur*_*eri 5

您必须先创建目录.

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);
Run Code Online (Sandbox Code Playgroud)