The first method: API
Using System.IO;
Using System.Runtime.InteropServices;
[DllImport ("kernel32.dll")]
public static extern IntPtr _lopen (string lppathname,int ireadwrite);
[DllImport ("kernel32.dll")]
public static extern bool CloseHandle (IntPtr hobject);
public const int of_readwrite=2;
public const int of_share_deny_none=0x40;
Public readonly IntPtr hfile_error=new IntPtr (-1);
private void Button1_Click (Object Sender,eventargs e)
{
string [email protected] "c:\temp\temp.bmp";
if (! File.exists (Vfilename))
{
MessageBox.Show ("The file does not exist!");
Return
}
IntPtr Vhandle=_lopen (vfilename,of_readwrite| Of_share_deny_none);
if (vhandle==hfile_error)
{
MessageBox.Show ("File is occupied!");
Return
}
CloseHandle (Vhandle);
MessageBox.Show ("Not occupied! ");
The second method: FileStream
public static bool Isfileinuse (string fileName)
BOOL Inuse=true;
FileStream Fs=null;
Try
{
Fs=new FileStream (Filename,filemode.open,fileaccess.read,fileshare.none);
Inuse=false;
}
Catch
{
}
Finally
{
if (fs!=null)
Fs. Close ();
}
return inUse;
}
Part of the Project Code (vb.net)
Sub Prepare ()
If file.exits (LOGRW) then File.delete (LOGRW)
Dim Bflag as Boolean=false
Try
Do
Shell ("cmd.exe/c rw.exe/command=limita.rw/logfile-limita.log", appwinstyle.hide,true,5000)
Threading.Thread.Sleep (1000)
while (Isfileinuse ("LimitA.log"))
Threading.Thread.Sleep (2000)
End while
If file.exists (LOGRW) Then
Dim all as String=my.computer.filesystem.readalltext (LOGRW)
If all.contains ("Read EC Byte ox01=0x80") Then
Bflag=true
End If
End If
Loop Until Bflag
Using SR as New StreamReader (LOGRW)
Do Until Sr. Endofstream
Dim s as STRING=SR. ReadLine
If s.contains ("Set environment RwLOCAL3") then
' Set Environment rwlocal3=4608 (DEC)
Limita=cdbl (S.split (New String () {"=", "("},stringsplitoptions.removeemptyentries (1))
Console.WriteLine ("Limit Current:" &limita)
logstr=logstr&vbcrlf& "Limit Current:" &limita
Exit do
End If
Loop
End Using
Catch ex as Exception
Console.writelien (ex. Message &err.description)
Environment.exit (1)
End Try
End Sub
Function Isfileinuse (ByVal fileName as String)
Dim InUse as Boolean=true
Dim FS as Filestream=nothing
Try
Fs=new FileStream (Filename,filemoe.open,fileaccess.read,fileshare.none)
Inuse=false
Catch ex as Exception
Finally
If (fs IsNot Nothing) Then
Fs. Close ()
End If
End Try
Return InUse
End Function
[C#.net] Two ways to determine whether a file is occupied