Check if a file is allready open by other application

  • Thread starter Thread starter Marcel Hug
  • Start date Start date
M

Marcel Hug

Hello NG !
I would like to test, if a file in my subtree is allready in use by an other
application.
Do anybody know how to get this information ? It is possible to get this
information ?

Thanks and regards.

Marcel Hug
 
try
{
using(FileStream fs = File.OpenWrite(strFileName)
{
if(fs == null)
return;
}
}
catch(UnauthorizedAccessException e)
{
//Here you know that the file is open by another app
}
 
Hello NG !
I would like to test, if a file in my subtree is allready in use by an other
application.
Do anybody know how to get this information ? It is possible to get this
information ?

Thanks and regards.

Marcel Hug

Try to open the file exclusively. If that files, then something else is
using the file. Ex:

FileStream fs = File.Open(fileName, FileMode.Open, FileAccess.Read,
FileShare.None);

Make sure to add proper exception handling around that and code to close
the file so it doesn't remain locked.
 
Hi,

It's possible but doing so is complex , I know if only one program (
ProcessExplorer ) that does it, no idea how though :(

The best you can do is trying to open the file with no sharing and catch the
exception if this fail, not the best way but it works


use this code

bool opened;
try{

FileStream fs = new FileStream( file, FileMode.Open, FileAccess.Write,
FileShare.None);
fs.Close();
opened = false;
}
catch( FileNotFoundException ex)
{
//what to do now?
opened = false;
}
catch( UnauthorizedAccessException e)
{
opened = true;
}


If you are 100% sure the file exist remove the first catch block


Cheers,
 
Hi,

OpenWrite create the file if it's not exist, maybe this is not the
intention. but only to test if the file exist and is open.


cheers,
 
Back
Top