可能重复:
Is there a way to check if a file is in use?
Check if a file is open
我怎么知道文件已经打开或正在使用中。
public bool FileIsLocked(string strFullFileName)
{
bool blnReturn = false;
System.IO.FileStream fs;
try
{
fs = System.IO.File.Open(strFullFileName, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None);
fs.Close();
}
catch (System.IO.IOException ex)
{
blnReturn = true;
}
return blnReturn;
}
我发现上面的代码无法正常工作
答案 0 :(得分:0)
从这里开始:Is there a way to check if a file is in use?
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;
}
答案 1 :(得分:0)
我在此之前已经回答:Check if a file is open
修改强>
FileInfo file = new FileInfo(path);
功能
protected virtual bool IsFileinUse(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();
}
return false;
}
答案 2 :(得分:0)
尝试按http://msdn.microsoft.com/en-us/library/b9skfh7s.aspx
抓取UnauthorizedAccessException
UnauthorizedAccessException
未从IOException
继承
http://msdn.microsoft.com/en-us/library/system.unauthorizedaccessexception.aspx