0

I am trying to rename a XML file in C# and following is my code

public static void RenameFile(this FileInfo fileInfo, string destFilePathName)
        {
            IsFileLocked(file);

            try
            {
                file.MoveTo(destFilePathName);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error '{fileInfo.Name}' to '{destFilePathName}': {ex}");
            }
        }

The IsFileLocked method is taken from [this answer][1]

private static bool IsFileLocked(FileInfo file)
        {
            try
            {
                using (FileStream stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    stream.Close();
                }
            }
            catch (IOException)
            {
                //the file is unavailable because it is:
                //still being written to
                //or being processed by another thread
                //or does not exist (has already been processed)
                return true;
            }

            //file is not locked
            return false;
        }

Even though the IsFileLocked method is returning false still I am getting the following exception at file.MoveTo(destFilePathName).

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

I am not using this file anywhere else. Any idea/suggestion why is this happening? [1]: https://stackoverflow.com/a/937558/8479386

Karan
  • 752
  • 2
  • 13
  • 34
  • The check is worthless, a race condition waiting to happen. But a good way to activate the installed anti-malware product, already over-eager by an executable file appearing from seemingly no-where, an access pattern that looks like probing and interested in XML files in general. Temporarily disable it and try again. – Hans Passant Mar 03 '21 at 14:32
  • Your `IsFileLocked` method may be causing this itself, as file closing is done asynchronously in MS Windows. I'd recommend putting a wait of 0.1 to 0.5 seconds in before you try to re-open the file. – RBarryYoung Mar 03 '21 at 14:33
  • Its giving same exception without the IsFileLocked method. – Karan Mar 03 '21 at 14:37

0 Answers0