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