";无法访问文件“”;写入文件时
本文关键字:文件 访问 quot | 更新日期: 2023-09-27 18:28:47
我一直在克隆记事本,遇到了一个问题。当我试图将文本框中的文本写入我创建的文件时,我会得到异常:
进程无法访问文件"C:''Users''opeyemi''Documents''b.txt"因为它正被另一个进程使用。
下面是我写的代码。如果能给我下一步该怎么做的建议,我将不胜感激。
private void Button_Click_1(object sender, RoutedEventArgs e)
{
SaveFileDialog TextFile = new SaveFileDialog();
TextFile.ShowDialog();
// this is the path of the file i wish to save
string path = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),TextFile.FileName+".txt");
if (!System.IO.File.Exists(path))
{
System.IO.File.Create(path);
// i am trying to write the content of my textbox to the file i created
System.IO.StreamWriter textWriter = new System.IO.StreamWriter(path);
textWriter.Write(textEditor.Text);
textWriter.Close();
}
}
您必须在using
中"保护"您的StremWriter
使用(read和write),如:
using (System.IO.StreamWriter textWriter = new System.IO.StreamWriter(path))
{
textWriter.Write(textEditor.Text);
}
不需要CCD_ 3。
您不需要System.IO.File.Create(path);
,因为StreamWriter
将为您创建文件(并且Create()
返回您在代码中打开的FileStream
)
从技术上讲,你可以:
File.WriteAllText(path, textEditor.Text);
这是一体化的,可以做所有事情(打开、写入、关闭)
或者,如果您真的想使用StreamWriter和File.Create:
using (System.IO.StreamWriter textWriter = new System.IO.StreamWriter(System.IO.File.Create(path)))
{
textWriter.Write(textEditor.Text);
}
(有一个StreamWriter
构造函数接受FileStream
)