Creating text file in C#

2020-04-17 06:41发布

问题:

I'm learning how to create text file in C# but I have a problem. 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)".

Where is the problem?

回答1:

The exception is indicating that your Directory C:\CSharpTestFolder doesn't exist. File.Create will create a file in existing folder/path, it will not create the full path as well.

Your check File.Exists(path) will return false, since the directory doesn't exists and so as the file. You need to check Directory.Exists on the folder first and then create your directory and then file.

Enclose your file operations in 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.

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



回答2:

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.

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(path);
using(StreamWriter sw = new StreamWriter(path))
    sw.WriteLine("Text");

...or all on one line

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


回答3:

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


回答4:

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