简体   繁体   English

在C#中创建文本文件

[英]Creating text file in C#

I'm learning how to create text file in C# but I have a problem. 我正在学习如何在C#中创建文本文件,但我遇到了问题。 I used this code: 我用过这段代码:

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

}

When I press the "Create" button, Visual Studio shows an error 'System.IO.DirectoryNotFoundException', which points at "File.Create(path)". 当我按下“创建”按钮时,Visual Studio会显示错误“System.IO.DirectoryNotFoundException”,它指向“File.Create(path)”。

Where is the problem? 问题出在哪儿?

The exception is indicating that your Directory C:\\CSharpTestFolder doesn't exist. 例外情况表明您的目录C:\\CSharpTestFolder不存在。 File.Create will create a file in existing folder/path , it will not create the full path as well. File.Create将在现有文件夹/路径中创建一个文件,它也不会创建完整路径。

Your check File.Exists(path) will return false, since the directory doesn't exists and so as the file. 您的检查File.Exists(path)将返回false,因为该目录不存在,因此该文件也是如此。 You need to check Directory.Exists on the folder first and then create your directory and then file. 您需要首先检查文件夹上的Directory.Exists ,然后创建您的目录,然后创建文件。

Enclose your file operations in try/catch . 将您的文件操作包含在try/catch You can't be 100% sure of File.Exists and Directory.Exists , there could be other process creating/removing the items and you could run into problems if you solely rely on these checks. 您无法100%确定File.ExistsDirectory.Exists ,可能有其他进程创建/删除项目,如果您完全依赖这些检查,则可能会遇到问题。

You can create Directory like: 您可以创建目录,如:

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

(You can call Directory.CreateDirectory without calling Directory.Exists , if the folder already exists it doesn't throw exception) and then check/create your file (您可以在不调用Directory.CreateDirectory情况下调用Directory.Exists ,如果该文件夹已存在则不会抛出异常)然后检查/创建您的文件

Well supposing that your directory exists (as you have said) then you have another problem 假设您的目录存在(正如您所说)那么您还有另一个问题

File.Create keeps locked the file that it creates, you cannot use the StreamWriter in that way. File.Create保持锁定它创建的文件,你不能以这种方式使用StreamWriter。

Instead you need to write 相反,你需要写

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

however all this is not really necessary unless you need to create the file with particular options ( see File.Create overload list ) because StreamWriter creates the file itself if it doesn't exist. 但是,除非您需要使用特定选项创建文件( 请参阅File.Create重载列表 ),否则所有这些都不是必需的,因为如果文件不存在,StreamWriter会自行创建文件。

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

...or all on one line ......或全部在一条线上

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

You have to create the directory first. 您必须先创建目录。

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

Try this. 尝试这个。

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

The File.AppendAllText(path, text) method will create a text file if it does not exist; File.AppendAllText(path, text)方法将创建一个文本文件(如果它不存在); append the text and will close the file. 附加文本并关闭文件。 If the file already exists, it will open the file and append the text to it and then close the file. 如果该文件已存在,它将打开该文件并将文本附加到该文件,然后关闭该文件。

The exception shows that the directory C:\\CSharpTestFolder does not exist. 该异常显示目录C:\\CSharpTestFolder不存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM