不能删除文件;进程无法访问该文件;

本文关键字:文件 访问 进程 删除 不能 | 更新日期: 2023-09-27 18:19:00

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

                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之后,我试图删除文件,但我不能:

"该进程不能访问该文件,因为它正在被另一个进程使用"

我能做什么?

不能删除文件;进程无法访问该文件;

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

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

如果这也不起作用,那么其他进程锁定了您的文件。

你为什么不这样写呢

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

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

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);