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());
}
}
}
First, you need to ensure that
fileStreamis disposed:See MSDN regarding the
usingstatement in place oftry/finally.BY THE WAY — What does
fileStreamdo here??? Nothing, it seems. Use this instead:And you should dispose the
TextFieldParseralso: