我有这个代码,想法是从文件中读取并删除文件。
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后, 我尝试删除该文件,但我不能:
“进程无法访问该文件,因为它正由另一个进程使用”
我该怎么办?
答案 0 :(得分:2)
在将代码括在using
语句中后尝试删除,如下所示:
using( StreamReader sr = new StreamReader(path) )
{
...
}
如果这也不起作用,则其他一些进程已锁定您的文件。
答案 1 :(得分:0)
你为什么不使用这样的东西
using (StreamReader sr= new StreamReader(your Path here))
{
// do your stuff
}
答案 2 :(得分:0)
要逐行读取文件,请尝试以下操作:
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);