Search code examples
c#filepathstreamwriter

Creating text file in C#


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?


Solution

  • 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