I want to copy files from one directory to another with overwriting. For the sake of consistency I want to lock all destination files before copying, overwrite them, then unlock.
This question suggests using a FileStream
for locking. However, both FileStream.Lock()
or FileShare.None
locks files from this process as well, making File.Copy()
throw an IOException
.
Here's a MVCE:
using System.Collections.Generic;
using System.IO;
namespace Test1
{
public class Program
{
public static void Main(string[] args)
{
var oldDir = @"c:\old\";
var newDir = @"c:\new\";
var locks = new List<FileStream>();
foreach (var item in Directory.EnumerateFiles(newDir))
{
var newLock = new FileStream(item, FileMode.Open, FileAccess.Read, FileShare.None);
locks.Add(newLock);
}
foreach (var item in Directory.EnumerateFiles(oldDir))
{
var dest = Path.Combine(newDir, Path.GetFileName(item));
File.Copy(item, dest, true);
}
}
}
}
Is using the same FileStream
for copying the only way, or can I still use File.Copy()
? How?