Click here to Skip to main content
16,016,925 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Can someone help me and show me a way of checking if a file is open such that i don't open the same file that is open...may be display a notification that the file is already open. Am using a Datagrid double click event...
here is my code..

C#
private void dgvDocs_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
       {
           Document document;

           string path;
           document = (Document)dgvDocs.CurrentRow.DataBoundItem;
           path = document.Documentpath;



           System.Diagnostics.Process.Start(path);

       }
Posted
Comments
joshrduncan2012 13-Nov-12 9:54am    
try this:

Process[] open_procs = Process.GetProcessesByName("nameOfProcess");
if(open_procs.Length > 0)
{
foreach(var proc in open_procs)
{
proc.Kill();
}
}
This kills any open processes you specify.
Code_Linc 16-Nov-12 9:47am    
Thanks for all the solutions however the first solution only works on documents yet i want to check for any file types....Please anyone with a solution help!

1 solution

C#
protected virtual bool IsFileinUse(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();
     }
     return false; 
}


Source: 1st Answer in this thread.[^]
 
Share this answer
 
Comments
MadMyche 29-Jan-18 10:32am    
A read-only file will fail this regardless if it is in use or not

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900