C# 用C语言创建文本文件#

C# 用C语言创建文本文件#,c#,file,path,streamwriter,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 =

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

}
当我按下“创建”按钮时,VisualStudio显示一个错误“System.IO.DirectoryNotFoundException”,它指向“File.Create(path)”


问题在哪里

异常表明您的目录
C:\CSharpTestFolder
不存在<代码>文件。创建将在现有文件夹/路径中创建文件,但不会创建完整路径

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

将文件操作包含在
try/catch
中。您无法100%确定
文件.Exists
目录.Exists
,可能存在其他创建/删除项目的过程,如果仅依靠这些检查,您可能会遇到问题

您可以创建如下目录:

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

(您可以调用
Directory.CreateDirectory
,而无需调用
Directory.Exists
,如果文件夹已存在,则不会引发异常)然后检查/创建文件您必须先创建目录

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);

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

如果将其创建的文件保持锁定状态,则不能以这种方式使用StreamWriter

相反,你需要写作

using(FileStream strm = File.Create(path))
using(StreamWriter sw = new StreamWriter(strm))
    sw.WriteLine("The first line!");
但是,除非您需要使用特定选项()创建文件,否则所有这些都不是必需的,因为StreamWriter会在文件不存在时创建文件本身

// File.Create(path);
using(StreamWriter sw = new StreamWriter(path))
    sw.WriteLine("Text");
…或全部在一条线上

File.WriteAllText(path, "The first line");
试试这个

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
不存在。

C:\CSharpTestFolder是否存在?如果您创建了代码,它是否工作?您是否具有编辑文件夹的适当权限?否,此文件不存在。当我手动创建此路径并再次运行该程序时,它会显示相同的错误,但该路径中的“test.txt”文件是由程序生成的,但当我打开它时,没有文本。我不确定,但我认为它有编辑权限。有关如何创建目录,请参阅此答案