hotcoder
hotcoder

Reputation: 3246

Error: The process cannot access the file because it is being used by another process

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

Upvotes: 1

Views: 6964

Answers (2)

taylor michels
taylor michels

Reputation: 528

Kevin is right that File TextFieldParser not being properly disposed will lock the file, making file.move throw an exception. In VB:

    Dim TextParser As New FileIO.TextFieldParser("C:\Users\Smith\Desktop\example.txt")
    TextParser.textFieldType = FileIO.FieldType.Delimited
    TextParser.SetDelimiters(",")

    While Not TextParser.EndOfData
        'process input
        'x = TextParser.ReadFields()
    End While

    TextParser.Dispose()

Now The following line will work without any problems

File.Move("C:\Users\Smith\Desktop\example.txt", "C:\Users\Smith\Desktop\Archive\example.txt")

Upvotes: 2

Kevin P. Rice
Kevin P. Rice

Reputation: 5733

First, you need to ensure that fileStream is disposed:

using (FileStream fileStream = new FileStream(file, FileMode.Open))
{
    readImport(file);
}

File.Move(file, Path.Combine(fullFolderPath, fullNewFileName));

See MSDN regarding the using statement in place of try/finally.

BY THE WAY -- What does fileStream do here??? Nothing, it seems. Use this instead:

readImport(file);
File.Move(file, Path.Combine(fullFolderPath, fullNewFileName));

And you should dispose the TextFieldParser also:

private void readImport(string fullFileName)
{
    using (TextFieldParser parser = new TextFieldParser(fullFileName))
    {
        parser.Delimiters = new string[] { "|" };
        parser.TrimWhiteSpace = true;
        parser.ReadLine();

        while (!(parser.EndOfData == true))
        {
            // dt.Rows.Add(parser.ReadFields());
        }
    }
}

Upvotes: 1

Related Questions