Creating text file in C#

放肆的年华 提交于 2019-12-02 00:55:24

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

Steve

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

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!