The process cannot access the file because it is being used by another process
Hey all
This is annoying, I want to perform a copy or move or read operation on a file but the file is already open in word or notepad, whatever.
No when I try for example to rename the file that is open in word the system tells me that I can't do it since word holds it.
How can I do the same in C#, meaning checking if the file is open and alert which application holds it.
Itzik
Hi,
What you can do is trying to aquire an exclusive share on the file, if you success it means that the file is not used by any other process.
Use the FileShare enumerator when you open the file, therefore your steps should be:
1) Try to open a file with None sharing
2) Close the handle (otherwise not even you can move it :-)
3) If there is no exception you can move the file.
Hope this helps.
Regards
I'd like to know the answer to this too (open a file for read that is already open by an external process).
As a workaround I copied the file (File.Copy(.....) ) and opened the copy. Its really annoying since my text editor can open a file that is currently locked by another process, the copy process *may* be reading the bytes when copying, but C# won't let me open for read access the very same file.
I came accros this problem too...
I'm trying to send a file from the Server i worte and I am SURE that no program use this file
and still i cant open the file in order to send it away, lets say that a program is using this file (its a BMP)
even then, Why we can't Open file for READ ONLY even if it is Locked.
FileOpen(hIn, sFile, OpenMode.Binary, OpenAccess.Read)
Thanks ahead, Alon.
When I tried your code, it does determine if the file is locked, but in doing so, it locks the file. I modified your code slightly to fix this.
Public Function FileIsLocked(ByVal strFullFileName As String) As Boolean
Dim blnReturn As Boolean = False
Dim fs As System.IO.FileStream
Try
fs = System.IO.File.Open(strFullFileName, IO.FileMode.OpenOrCreate, IO.FileAccess.Read, IO.FileShare.None)
fs.Close()
Catch ex As System.IO.IOException
blnReturn = True
End Try
Return blnReturn
End Function