0

I have placed a text file in c:\my_files\test1.txt. Using C# I need to check whether the file is in an open state. If it is, I need to close the editor.

In the below code it doesn't go to the catch block if the file is in open state.

string path = @"c:\my_files\test1.txt";

FileStream stream = null;
try
{
    stream = File.Open( path, FileMode.Open, FileAccess.Read, 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;
    Console.WriteLine("true");
}
finally
{
    if (stream != null)
        stream.Close();
}
CDspace
  • 2,639
  • 18
  • 30
  • 36
  • Possible duplicate of [Is there a way to check if a file is in use?](http://stackoverflow.com/questions/876473/is-there-a-way-to-check-if-a-file-is-in-use) – huse.ckr Oct 06 '16 at 12:20
  • 1
    So since you already have the code from the possible duplicate, is your question really how to close a process using a particular file? – Jeff B Oct 06 '16 at 12:40
  • @JeffBridgman No. That code doesn't go to catch block even text file opened externally. I too tested the code.. It doesn't work – Balagurunathan Marimuthu Oct 06 '16 at 12:42
  • 1
    The head line is not correct. You should simple write text file - not notepad file. – codelab Oct 06 '16 at 12:53
  • 2
    What does it mean, "open state"? Notepad doesn't keep the file opened, and there's plenty of other editors that may behave the same way or differently. Are you asking how to detect if notepad has a particular file opened? In that case, Notepad has no API you could use for that, so there's no supported way of doing that. What are you *really* trying to do? What problem are you trying to solve, what use case? – Luaan Oct 06 '16 at 13:00
  • sorry for the confusion.. I need to check whether the text file is open? if so i need to close that text file – Diwakar Narasimman Oct 06 '16 at 13:09

1 Answers1

2

You cannot determine whether the Notepad.exe application has a file opened in memory - it does not retain an open file stream. You might be able to check that the Notepad application processes window title has the name of the file in it, but it does not have the file path, so this is extremely fragile.

Since Notepad does not have the file open, its not meaningful to attempt to close the file. You can try to close Notepad if you think the file is has copied to its memory buffer is the one you think it is ...

PhillipH
  • 6,182
  • 1
  • 15
  • 25