错误:该进程无法访问该文件,因为该文件正在被另一个进程使用
我正在 ASP.NET 应用程序中工作并读取管道分隔的文本文件。读取文件后,当我尝试重命名文件(通过使用“移动”功能)时,出现错误:“该进程无法访问该文件,因为它正在被另一个进程使用。”。在重新启动 Windows 之前,我无法手动重命名或删除该文件。 我的代码如下:
FileStream fileStream = new FileStream(file, FileMode.Open);
try
{
readImport(file);
}
finally
{
fileStream.Close();
}
File.Move(file, Path.Combine(fullFolderPath, fullNewFileName));
处理文件的函数是:
private void readImport(string fullFileName)
{
try
{
TextFieldParser parser = new TextFieldParser(fullFileName);
parser.Delimiters = new string[] { "|" };
parser.TrimWhiteSpace = true;
parser.ReadLine();
while (!(parser.EndOfData == true))
{
// dt.Rows.Add(parser.ReadFields());
}
}
}
I'm working in ASP.NET application and reading a pipe delimited text file. After reading the file when I try to rename the file (by using "Move" function) I get the error: "The process cannot access the file because it is being used by another process.". I cannot either rename or delete the file manually until I restart the Windows.
My code is following:
FileStream fileStream = new FileStream(file, FileMode.Open);
try
{
readImport(file);
}
finally
{
fileStream.Close();
}
File.Move(file, Path.Combine(fullFolderPath, fullNewFileName));
and the function that processes the file is:
private void readImport(string fullFileName)
{
try
{
TextFieldParser parser = new TextFieldParser(fullFileName);
parser.Delimiters = new string[] { "|" };
parser.TrimWhiteSpace = true;
parser.ReadLine();
while (!(parser.EndOfData == true))
{
// dt.Rows.Add(parser.ReadFields());
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Kevin 是对的,File TextFieldParser 未正确处理会锁定文件,从而使 file.move 抛出异常。在 VB 中:
现在以下行将正常工作
Kevin is right that File TextFieldParser not being properly disposed will lock the file, making file.move throw an exception. In VB:
Now The following line will work without any problems
首先,您需要确保释放
fileStream
:请参阅 MSDN 关于使用
using
语句 代替try/finally
。顺便说一句——
fileStream
在这里做什么???似乎没什么。改用它:并且您还应该处置
TextFieldParser
:First, you need to ensure that
fileStream
is disposed:See MSDN regarding the
using
statement in place oftry/finally
.BY THE WAY -- What does
fileStream
do here??? Nothing, it seems. Use this instead:And you should dispose the
TextFieldParser
also: