0
我想檢查一個特定的Excel文件是否已經打開。否則,當我在C#程序中重新打開相同的文件時,它將以只讀格式打開。有什麼方法可以找出文件是否已經打開?有沒有辦法以編程方式檢查是否打開Excel文件
我想檢查一個特定的Excel文件是否已經打開。否則,當我在C#程序中重新打開相同的文件時,它將以只讀格式打開。有什麼方法可以找出文件是否已經打開?有沒有辦法以編程方式檢查是否打開Excel文件
如果如果由其他程序的代碼可以幫助你看着辦吧開了,但您將無法打開該文件
<!-- language: c# -->
protected virtual 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;
}
(但你不能用它做任何事情時,文件必須從打開它的程序中關閉)
爲什麼只是複製代碼而不指向[原始答案](http://stackoverflow.com/a/937558/362938)? – detunized 2012-07-11 11:03:44
如果要打開該文件僅用於閱讀目的,請在打開文件之前製作一份副本,這將解決「只讀」問題 – Shai 2012-07-11 07:07:39
可能的重複[有沒有辦法檢查一個文件是否正在使用?](http://stackoverflow.com/questions/876473/is-there-a-way-to-check-if-a-file-is-in -use) – Shai 2012-07-11 07:08:10
@shai不,我想要關閉文件,如果它已經打開,那麼需要創建新的表格並寫入數據。 – 2012-07-11 07:28:25