Click here to Skip to main content
13,594,656 members
Rate this:
 
Please Sign up or sign in to vote.
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..

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 13-Nov-12 3:46am
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

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

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.[^]
  Permalink  
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Cookies | Terms of Service
Web02-2016 | 2.8.180621.3 | Last Updated 13 Nov 2012
Copyright © CodeProject, 1999-2018
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100