0

In my application I need to get the filename of the file which is opened. I found several threads about how to get the name of the process which is running but nothing about how I can get the file name (or path, at least I need the file name) of the current opened document.

I know how I can get the path:

FileInfo info = new FileInfo(fileName)
string path = info.FullName;

But to use this I need the string "fileName" which is the name of the current opened file.

Any suggestions? :)

tshepang
  • 12,111
  • 21
  • 91
  • 136
Therk
  • 391
  • 6
  • 23
  • 1
    Because it's not easy. You have to enumerate handles of a given process, select file handles and then find to what they refer. All done with unmanaged APIs. – Adriano Repetti Apr 15 '14 at 09:57
  • http://stackoverflow.com/questions/177146/how-do-i-get-the-list-of-open-file-handles-by-process-in-c – Sajeetharan Apr 15 '14 at 10:05

3 Answers3

0

If you have the path of the file, then you can use the following code to get the filename:

string path = string.Empty;
string fileName = Path.GetFileName(path);
Jamie
  • 3,031
  • 5
  • 36
  • 59
0

There is an API for that you should P/Invoke: try GetFileInformationByHandleEx http://msdn.microsoft.com/en-us/library/aa364953(VS.85).aspx, that requires the file handle to work with.

Felice Pollano
  • 32,832
  • 9
  • 75
  • 115
0

Try this function , give it the path of the file, it will return you false if the file is open,

public bool ckIsFileOpnen(string sFileFullPath)
        {
            try
            {
                using (Stream stream = new FileStream(sFileFullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
                {
                }
                return true; //file is available for write
            }
            catch { }

            return false;
        }