распространенный метод:
Код: Выделить всё
protected virtual bool IsFileLocked(FileInfo file)
{
try
{
using(FileStream stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None))
{
stream.Close();
}
}
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 true;
}
//file is not locked
return false;
}
Я могу проверить с помощью метод, если файл изменяется в течение короткого периода времени, но это будет очень неэффективно, если повторять много файлов (т. е. 500 мс для более чем 1000 файлов будут составлять 8 минут ожидания).
один из подходов, который действительно работает состоит в том, чтобы попытаться выполнить File.Move() и посмотреть, возвращает ли он исключение. если да, то файл занят. я не знаю
Код: Выделить всё
t like this approach because in case of problems it could damage the file since it
это будет реализованный метод
Код: Выделить всё
public bool IsFileLocked(string filePath)
{
try
{
string tempFilePath = filePath + ".tmp";
File.Move(filePath, tempFilePath);
File.Move(tempFilePath, filePath);
return false; // File is not locked
}
catch (IOException)
{
return true; // File is locked
}
catch (UnauthorizedAccessException)
{
return true; // File is locked or access is denied
}
}
Подробнее здесь: https://stackoverflow.com/questions/787 ... ng-written