2

I have a text file and I want to check if it's open already. the problem is that it is posible to open the file multiple times and there is no exception.

I tried:

stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);

No exception.

I also tried

using (Stream stream = new FileStream("MyFilename.txt", FileMode.Open))

no exception.

And even

System.Diagnostics.Process.GetProcessesByName("MyFilename.txt").Length < 1

but even if the file is open it returns 0.

MyFilename.txt is just a name, in the real code it's the real file path.

What can I write insted?

Thanks! Grace

Rahul
  • 5,603
  • 6
  • 34
  • 57
user2348001
  • 45
  • 1
  • 6

2 Answers2

2

If the notepad doesn't lock exclusively the text file then you need to use a different approach

Process[] pList = Process.GetProcessesByName("notepad");
foreach(Process p in pList)
{
    if(p.MainWindowTitle.Contains("MyFilename.txt")
       ......
}

Of course this is not a foolprof solution. I could open the file with WordPad or some other text editor and if it there is no lock we have again the same problem

However, if you succed on exclusively open the file, then it is a Notepad problem to save its changes

Steve
  • 213,761
  • 22
  • 232
  • 286
1

Yes there is a way using FileStream like

protected virtual bool IsFileUsed(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 in use
    return false;
}
Rahul
  • 5,603
  • 6
  • 34
  • 57
  • @Rahul: when you copy paste the code, make sure to link to the original post. Much useful info there - http://stackoverflow.com/questions/876473/is-there-a-way-to-check-if-a-file-is-in-use – A G May 27 '13 at 10:45
  • i tried this same thing into my own problem once that's is why i am mentioning that code here.i even get that code from the same post you mentioned. – Rahul May 27 '13 at 10:47
  • Thanks but I already read this in my research. Nothing there helped, I guess because it is possible to open notepad file more than once – user2348001 May 27 '13 at 10:49