In Java and C#, is there any function to check if a file is used or not, like the error message we get when we try to delete a used file?
If not, what is another good way to check it?
In Java and C#, is there any function to check if a file is used or not, like the error message we get when we try to delete a used file?
If not, what is another good way to check it?
It's generally advised not to check if a file is being used. It's pointless.
Say you have the following code:
if(file is not being used)
open file
Even if the if
statement evaluates as true
, there's no guarantee that the file won't be being used by the time you try to open it. So, just do whatever you want to do with the file, and handle any exceptions that might be thrown.
The case with throwing an exception is only proper one and expected behavior for such case.
The reason of that came from the OO principles. You request an object to perform some action. In case it can not finish it as expected it should return this. I language like C++ where exceptions ware not such popular an error code would be returned that developer should check. This is error prone, so for later languages the API designers has introduced the exception. That gives developer proper control on the code.
Accessing resources is complex task, lot of cases has to be considered and it is always a multithred case.
Instead of approaching to the issue that file can not be deleted and detect that. You should focus on logic that should be applied when case like this occurs.
Solution for Java:
You can use Files and method delete(java.nio.file.Path)
.
This method throw an SecurityException
when file is not allowed to be deleted.
Or you can use use the system SecurityManager
SecurityManager security = System.getSecurityManager();
securty.checkDelete(String file)
Throws a SecurityException if the calling thread is not allowed to delete the specified file.
Solution for C#:
The same rule apply to C#, System.IO.File.Delete
it will thrown an UnauthorizedAccessException
First check if the file exists (File.Exists
) if so try to open for write within try
and catch
block, if exception is generated then it is used by another process. However finding something through exception is not the best way!
You can try this :
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;
}