c# - 为什么在 StreamReader.Read 周围使用 using() {} 允许之后删除文件?

标签 c# winforms streamreader using system.io.file

所以我在为学校项目试用 Windows 窗体时一直遇到错误:

System.IO.IOException('The process cannot access the file 'C:\XXXX\YYYY.txt' because it is being used by another process.'

尝试通过 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();
}

最佳答案

在您的第一种方法中,由于您没有Close()ing 或Dispose()ing 您的StreamReader,相关文件handle 将被保留,直到 StreamReader 被垃圾收集器收集,这可能需要很多秒,甚至几分钟(请不要试图控制或影响 GC)。

在您的第二种方法中,using 范围在范围的末尾放置(并关闭)StreamReader(结束 } 匹配using),这是使用任何实现了 IDisposable 的类时的正确做法。然后释放文件的所有句柄,允许删除文件。 using block 也有 try/finally block 的保证,所以即使有 IO 异常也会调用 Dispose:

using(StreamReader Reader = new StreamReader(path)) // try {StreamReader Reader = ...}
{
     ...
} <- equivalent to finally {Reader.Dispose();}

但是,由于您似乎只想立即具体化行分隔文本文件中的所有行,您可以使用 File.ReadAllLines 一步完成此操作- 即根本不需要 StreamReader:

var tempStore = string.Join(Environment.NewLine, File.ReadAllLines(path));

关于c# - 为什么在 StreamReader.Read 周围使用 using() {} 允许之后删除文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48040898/

相关文章:

c# - CS0117 - Xamarin 未检测到 'Resources' 文件夹和文件

c# - 在应用程序中管理时区和位置感知时间?

c# - 从给定索引的 DataGridView 中删除行

c# - GZipStream with StreamReader.ReadLine 只读取第一行

c# - Angular + ASP.NET Core Web API : 404 on new controller endpoints

c# - 如何通过 LINQ 选择队列中最常出现的值?

vb.net - 循环遍历表单中的所有文本框,包括分组框内的文本框

c# - 在 BackgroundWorker 中调用 ShowDialog

c# - Streamreader 和 "Index was outside the bounds of the array"错误

c# - StreamReader ReadLine 抛出异常而不是返回 null