【发布时间】:2015-03-05 14:28:52
【问题描述】:
我正在学习如何在 C# 中创建文本文件,但我遇到了一个问题。我使用了这段代码:
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)”。
问题出在哪里?
【问题讨论】:
-
C:\CSharpTestFolder 是否存在?如果您创建它,您的代码是否有效?您是否具有编辑文件夹的适当权限?
-
不,此文件不存在。当我手动创建此路径并再次运行程序时,它显示相同的错误,但该路径中的“test.txt”文件是由程序生成的,但是当我打开它时,没有文本。我不确定,但我认为它有编辑权限。
标签: c# file path streamwriter