在C#中创建文本文件 [英] Creating text file in C#
问题描述
我正在学习如何在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);
}
当我按下创建"按钮时,Visual Studio显示错误"System.IO.DirectoryNotFoundException",它指向"File.Create(path)".
When I press the "Create" button, Visual Studio shows an error 'System.IO.DirectoryNotFoundException', which points at "File.Create(path)".
问题出在哪里?
推荐答案
该异常表明您的目录C:\CSharpTestFolder
不存在. File.Create
将在现有文件夹/路径中创建文件,也不会创建完整路径.
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.
您的支票File.Exists(path)
将返回false,因为该目录不存在,因此不存在该文件.您需要检查 Directory.Exists
首先在文件夹上,然后创建目录,然后创建文件.
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.
将文件操作包含在try/catch
中.您不能100%确定File.Exists
和Directory.Exists
,可能会有其他过程创建/删除项目,如果仅依靠这些检查,则可能会遇到问题.
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);
(您可以在不调用Directory.Exists
的情况下调用Directory.CreateDirectory
,如果该文件夹已经存在,则不会引发异常),然后检查/创建您的文件
(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
这篇关于在C#中创建文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!