I am using File.GetCreationTime
to sort few files. After using this function when I am trying to move using File.Move
I get an error:
The process cannot access the file because it is being used by another process.
Here is the code:
foreach (var f in Directory.GetFiles(source))
{
DateTime creation = File.GetCreationTime(f);
var fileDest = Path.Combine(destination, creation.Year.ToString());
if (!Directory.Exists(fileDest))
{
Directory.CreateDirectory(fileDest);
}
File.Move(f, Path.Combine(fileDest, Path.GetFileName(f)));
}
Does File.GetCreationTime
gets the filehandle?
What am I doing wrong?
I have used the retry pattern suggested but still the code fails:
foreach (var f in Directory.GetFiles(source))
{
DateTime creation = File.GetCreationTime(f);
var fileDest = Path.Combine(destination, creation.Year.ToString());
if (!Directory.Exists(fileDest))
{
Directory.CreateDirectory(fileDest);
}
for (int i = 1; i <= 3; ++i)
{
try
{
File.Move(f, Path.Combine(fileDest, Path.GetFileName(f)));
break;
}
catch (IOException e)
{
if (i == 3)
throw;
Thread.Sleep(1000);
}
}
}