【问题标题】:Can't delete a file "The process cannot access the file"无法删除文件“进程无法访问文件”
【发布时间】:2012-01-29 03:01:57
【问题描述】:

我有这段代码,想法是从文件中读取并删除文件。

                StreamReader sr = new StreamReader(path);

                s = sr.ReadLine();
                if ((s != null))
                {
                 sr.ReadLine();
                  do
                   {
                   // I start to read and get the characters

                   }while (!(sr.EndOfStream));
                 }
                 sr.close();

然后在关闭streamReader之后, 我尝试删除该文件,但我不能:

“该进程无法访问该文件,因为它正被另一个进程使用”

我能做什么?

【问题讨论】:

  • 是excel文件还是其他文件?
  • 代码(片段)看起来过于复杂,从你描述的目标来看有点脆弱。显示完整的代码/功能,至少到您尝试删除文件的部分。
  • 这是一个txt代码,我用sr.Dispose()试了一下,还是不行
  • 你能说出路径变量包含什么吗?
  • 关闭记事本 :)

标签: c# file stream delete-file


【解决方案1】:

using 语句中包含您的代码后尝试删除,如下所示:

using(  StreamReader sr = new StreamReader(path) ) 
{ 
    ...
}

如果这也不起作用,则说明其他进程已锁定您的文件。

【讨论】:

  • 啊,又是一位快乐的客户。很高兴能帮上忙。
【解决方案2】:

你为什么不用这样的东西

using (StreamReader sr= new StreamReader(your Path here))
{
    // do your stuff
}

【讨论】:

    【解决方案3】:

    要逐行读取文件,请尝试以下操作:

    using (var reader = new StreamReader(path))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            // do something with the line that was just read from the file
        }
    }
    
    // At this stage you can safely delete the file
    File.Delete(path);
    

    或者如果文件很小,你甚至可以加载内存中的所有行:

    string[] lines = File.ReadAllLines(path);
    // Do something with the lines that were read
    ...
    // At this stage you can safely delete the file
    File.Delete(path);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多