我正在编写一个应用程序,等待将文件复制到文件夹,复制完文件后,然后尝试打开文件。
我遇到一个文件长度为零的问题。我相信这是因为文件没有完全完成复制到磁盘。
我遵循了https://stackoverflow.com/a/937558/5330854解决方案,其中检查了文件是否被锁定,但这仍然允许我打开长度为零的文件(我假设是否正在将文件复制到磁盘上) ,那么当文件不为零时,它将被锁定,而我将无法打开它)。
有什么主意如何检查文件是否已完成复制到磁盘吗?
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;
}