I'm writing an application that awaits for a file to be copied to a folder, when the file has been copied, I then attempt the open the file.
I'm experiencing an issue where sometime the file length is zero. I believe this is because the file as not fully completed copying to the disk.
I have followed https://stackoverflow.com/a/937558/5330854 solution where I check if the file is locked, but this still allows me to open the file with the length being zero (I'd assume if the file in progress of being copied to disk, then this would be locked and I wouldn't be able to open it), when the file is not zero.
Any idea how to check if a file has finished copying to disk?
while (stream == null && IsWithingTimeCap(startTime))
{
stream = GetFileStream(fileInfo);
if (stream == null)
{
Thread.Sleep(5000);
}
}
if (fileInfo.Length == 0)
{
//log
}
private static Stream GetFileStream(IFileInfo fileInfo)
{
Stream stream = null;
try
{
stream = fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.None);
}
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 null;
}
return stream;
}