Share via


how to check if a file is open in vb.net?

Question

Thursday, January 24, 2013 11:22 AM

Hi All

I use a command for open a file for example:

Process.Start(EZCADFile_Copy_Path)

now I want to check if file is open :

1- close file

2- open file again

how to check if a file is open?

if file is open then

close file (EZCADFile_Copy_Path)

Process.Start(EZCADFile_Copy_Path)

end if

thanks a lot****

Best Regard Fatemeh AmirAfshar

All replies (3)

Thursday, January 24, 2013 1:13 PM ✅Answered | 2 votes

Fatemah Amir

Hope this helps as below code checks if file is open in vb.net. modify accordingly

    Try
            Dim fOpen As IO.FileStream = IO.File.Open("your file name", IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.None)
            fOpen.Close()
            fOpen.Dispose()
            fOpen = Nothing
        Catch e1 As IO.IOException
            'File Open by some one else..
        Catch e2 As Exception
        End Try

 


Friday, January 25, 2013 6:54 AM ✅Answered | 1 vote

Another way to check whether a file is in use is to call the CreateFile API. If a file is in use, the handle return is invalid.

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern SafeFileHandle CreateFile(string lpFileName,
    FileSystemRights dwDesiredAccess, FileShare dwShareMode, IntPtr
    securityAttrs, FileMode dwCreationDisposition, FileOptions
    dwFlagsAndAttributes, IntPtr hTemplateFile);

        const int ERROR_SHARING_VIOLATION = 32;

        private bool IsFileInUse(string fileName)
        {
            bool inUse = false;

            SafeFileHandle fileHandle = 
            CreateFile(fileName, FileSystemRights.Modify, 
                  FileShare.Write, IntPtr.Zero,                  
                  FileMode.OpenOrCreate, FileOptions.None, IntPtr.Zero);

            if (fileHandle.IsInvalid)
            {
               if (Marshal.GetLastWin32Error() == 
                   ERROR_SHARING_VIOLATION)
               {
                   inUse = true;
               }           
            }
            fileHandle.Close();
            return inUse;
        }

Reference link:  FAQ: How do I check whether a file is in use? 

Best regards,

Shanks Zen
MSDN Community Support | Feedback to us
Develop and promote your apps in Windows Store
Please remember to mark the replies as answers if they help and unmark them if they provide no help.


Wednesday, November 14, 2018 7:57 PM

Sure wish they would lock old threads that have an answer.

"Those who use Application.DoEvents() have no idea what it does and those who know what it does never use it."

- from former MSDN User JohnWein

SerialPort Info

Multics - An OS ahead of its time.