There is no guarantee that the list you get, at any point of time, is going to stay the same the next second as somebody else might take control of the file by the time you come back to them.
I see one way though - "LOCK" the files that you want to replace by getting their corresponding FileStream objects. This way you are sure that you have locked all "available" files by opening them and then you can replace them the way you want.
public void TestGivenFiles(List<string> listFiles)
{
List<FileStream> replaceAbleFileStreams = GetFileStreams(listFiles);
Console.WriteLine("files Received = " + replaceAbleFileStreams.Count);
foreach (FileStream fileStream in replaceAbleFileStreams)
{
// Replace the files the way you want to.
fileStream.Close();
}
}
public List<FileStream> GetFileStreams(List<string> listFilesToReplace)
{
List<FileStream> replaceableFiles = new List<FileStream>();
foreach (string sFileLocation in listFilesToReplace)
{
FileAttributes fileAttributes = File.GetAttributes(sFileLocation);
if ((fileAttributes & FileAttributes.ReadOnly) != FileAttributes.ReadOnly)
{ // Make sure that the file is NOT read-only
try
{
FileStream currentWriteableFile = File.OpenWrite(sFileLocation);
replaceableFiles.Add(currentWriteableFile);
}
catch
{
Console.WriteLine("Could not get Stream for '" + sFileLocation+ "'. Possibly in use");
}
}
}
return replaceableFiles;
}
That said, you are better off trying to replace them one by one and and ignore the ones that you can't.