【发布时间】:2017-12-31 07:53:53
【问题描述】:
所以我在为一个学校项目试用 Windows 表单并一直遇到错误:
System.IO.IOException('进程无法访问文件'C:\XXXX\YYYY.txt',因为它正被另一个进程使用。'
尝试通过button_click 事件删除文件 (File.Delete(path);) 时。
原来,当我改变以下方法时:
private void updateTxt(){
String tempStore = "";
iDLbl1.Text = "ID:" + id;//iDLbl1 is ID Label 1
try
{
StreamReader Reader = new StreamReader(path);
while (!Reader.EndOfStream)
{ tempStore += Reader.ReadLine() + "\n"; }
}
catch { noIDLbl.Visible = true; }
rTxtBox.Text = tempStore;//rTxtBox is Rich Text Box
}
到
private void updateTxt(){
String tempStore = "";
iDLbl1.Text = "ID:" + id;//iDLbl1 is ID Label 1
try
{
using(StreamReader Reader = new StreamReader(path))
{
while (!Reader.EndOfStream)
{ tempStore += Reader.ReadLine() + "\n"; }
}
}
catch { noIDLbl.Visible = true; }
rTxtBox.Text = tempStore;//rTxtBox is Rich Text Box
}
异常停止弹出。 虽然代码有效,但我根本不知道是什么原因造成的......逻辑似乎没有为我点击,所以任何人都知道为什么会发生这种情况或有更合乎逻辑的解决方案吗?如果需要请要求澄清,这是构造函数以防万一:
public FindID(String ID)
{
id = ID;
path = @"C:\XXXX\YYYY\"+ID+".txt";
InitializeComponent();
updateTxt();
}
【问题讨论】:
-
是的,打开的文件需要再次关闭才能删除。您编写的代码不是 File.ReadAllText() 的有用替代品。
标签: c# winforms streamreader using system.io.file