应该是FTP还在使用文件。 FileStream fs; ReadFile: try { fs = File.OpenRead("TestFile.txt"); } catch(IOException) { //文件可能被占用 } 好一点的方法是使用APIInstead of doing that, I would recommend declaring the CreateFile API function so that you can call it through the P/Invoke layer. The CreateFile function will return an error code if you can not access the file, which is much cleaner than handling the exception.Once you have that, if you are able to open the file with the CreateFile API, then you can pass the handle to the FileStream constructor, which takes a file handle.
FileStream fs;
ReadFile:
try
{
fs = File.OpenRead("TestFile.txt");
}
catch(IOException)
{
//文件可能被占用
}
好一点的方法是使用APIInstead of doing that, I would recommend declaring the CreateFile API
function so that you can call it through the P/Invoke layer. The CreateFile
function will return an error code if you can not access the file, which is
much cleaner than handling the exception.Once you have that, if you are able to open the file with the CreateFile
API, then you can pass the handle to the FileStream constructor, which takes
a file handle.
fileHandle = CreateFileWrapper.CreateFile(e.FullPath,
EFileAccess.GenericRead,
EFileShare.Read,
IntPtr.Zero,
ECreationDisposition.OpenExisting,
EFileAttributes.Readonly,
IntPtr.Zero);
if( !fileHandle.IsInvalid ) {
break;
} else {
Thread.Sleep(1000);
}
}
从这里http://pinvoke.net/default.aspx/kernel32/CreateFile.html找到CreateFile的C#封装写法。