3 回答

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超4個(gè)贊
對于您面臨的問題,只有解決方法。
開始復(fù)制之前,請檢查文件ID是否正在處理中。您可以調(diào)用以下函數(shù),直到獲得False值為止。
第一種方法,直接從此答案復(fù)制:
private bool IsFileLocked(FileInfo file)
{
FileStream stream = null;
try
{
stream = file.Open(FileMode.Open, FileAccess.ReadWrite, 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 true;
}
finally
{
if (stream != null)
stream.Close();
}
//file is not locked
return false;
}
第二種方法:
const int ERROR_SHARING_VIOLATION = 32;
const int ERROR_LOCK_VIOLATION = 33;
private bool IsFileLocked(string file)
{
//check that problem is not in destination file
if (File.Exists(file) == true)
{
FileStream stream = null;
try
{
stream = File.Open(file, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (Exception ex2)
{
//_log.WriteLog(ex2, "Error in checking whether file is locked " + file);
int errorCode = Marshal.GetHRForException(ex2) & ((1 << 16) - 1);
if ((ex2 is IOException) && (errorCode == ERROR_SHARING_VIOLATION || errorCode == ERROR_LOCK_VIOLATION))
{
return true;
}
}
finally
{
if (stream != null)
stream.Close();
}
}
return false;
}

TA貢獻(xiàn)1812條經(jīng)驗(yàn) 獲得超5個(gè)贊
這是一個(gè)舊線程,但我將為其他人添加一些信息。
我在編寫PDF文件的程序中遇到了類似的問題,有時(shí)它們需要30秒才能呈現(xiàn)..這與我的watcher_FileCreated類在復(fù)制文件之前等待的時(shí)間相同。
文件未鎖定。
在這種情況下,我檢查了PDF的大小,然后等待2秒鐘再比較新的大小,如果它們不相等,則該線程將休眠30秒鐘,然后重試。
- 3 回答
- 0 關(guān)注
- 663 瀏覽
添加回答
舉報(bào)