Home > OS >  Detect if file is open locally or over share
Detect if file is open locally or over share

Time:12-25

I'm trying to check if a file is open in Win32:

bool CheckFileUnlocked(const TCHAR *file)
{
    HANDLE fh = ::CreateFile(file, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
    if(fh != NULL && fh != INVALID_HANDLE_VALUE) {
        return (CloseHandle(fh) == TRUE);
    }
    return false;
}

I need to be able to distinguish if a file is opened locally, in that case the function must return true against if it is opened from a shared path. The file itself is accessible over network, and is mapped in a shared drive. The function above tries to open file with exclusive access. I tried adding else clause reducing to:

bool CheckFileUnlocked(const TCHAR *file)
{
    HANDLE fh = ::CreateFile(file, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
    if(fh != NULL && fh != INVALID_HANDLE_VALUE) {
        return (CloseHandle(fh) == TRUE);
    } else {
        fh = ::CreateFile(file, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
        if(fh != NULL && fh != INVALID_HANDLE_VALUE) {
            return (CloseHandle(fh) == TRUE);
        }
    }
    return false;
}

But I still couldn't figure out if the file was open locally or over network on another system. I also tried LockFileEx() and UnlockFileEx(), but I'm guessing these might be wrong approaches. How do I solve this without actually querying the Application (LibreOffice Writer), assuming it provides API level access to this condition (LO actually provides a popup upon opening said document and allows to open it as ReadOnly, or open a Copy)?

CodePudding user response:

You can try GetFileInformationByHandleEx:

  • FileRemoteProtocolInfo should return properties of network access, and probably should fail on local files
  • FileStorageInfo should return properties of the storage, it might fail on network (but need to verify that)
  • Related