且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查一个文本文件是否在记事本中打开

更新时间:2023-11-25 16:12:34

扩大我的评论。只有在应用程序保持打开的情况下才会锁定文件。 Word例如将打开文件,读取流并维护句柄,以便其他应用程序不能删除该文件,而用户正在处理它。



记事本和其他应用程序,只需打开文件,读取整个流,然后关闭文件释放他们拥有的锁。这意味着该文件不再被锁定,可以由另一个应用程序编辑,甚至删除和记事本将不在意,因为它有自己的副本在内存中。

你可以尝试和获取记事本的实例,并检查是否打开文件,但这最终不是一个好主意。如果文件没有被锁定,那么你应该可以***地做你想要的。


how to find whether specific .txt file is opened in notepad?

I have tried solutions mentioned here

Is there a way to check if a file is in use?

But they work fine for Word and pdf file but not working for txt file opened in Notepad.

here is code I have wrote.

public bool IsFileOpen(string strFileName)
{
    bool retVal = false;
    try
    {
        if (File.Exists(pstrFileName))
        {
            using (FileStream stream = File.OpenWrite(pstrFileName))
            {
                try
                {    
                }
                catch (IOException)
                {
                    retVal = true;
                }
                finally
                {
                    stream.Close();
                    stream.Dispose();
                }
            }
        }
    }
    catch (IOException)
    { //file is opened at another location 
        retVal = true;
    }
    catch (UnauthorizedAccessException)
    { //Bypass this exception since this is due to the file is being set to read-only 
    }
    return retVal;
} 

am i missing somthing here.??

My requirement: I have application which works similar to VSS. When user checks out specific file and opens ,and try to check in the same, while it has opened. Application is suppose to throw a warning message.For that i have used the above functionality.Its working fine for word and pdf.

To expand on my comment. A file is only locked if a handle is kept open by an application. Word for example will open the file, read in the stream and maintain the handle so that other applications cannot delete that file while the user is working on it.

Notepad, and other applications, just open the file, read in the entire stream and then close the file releasing the lock they have. This means that the file is no longer locked and can be edited by another application or even deleted and Notepad will not care as it has its own copy in memory.

You could try and hack around with getting instances of Notepad and checking if a file is open but this is ultimately not a great idea. If the file is not locked then you should be free to do what you want with it.