简体   繁体   中英

Checking if the file is already in use before opening (network drive, C#)

如果文件(在本地网络驱动器上)已经被使用,在打开之前是否有任何方法可以检查.Net?

You should try to access it and if it failed, you either don't have required permissions (which you can check with GetAccessControl) or it's locked by another process.

But I don't think there is any reliable measure to distinguish a lock and a permission failure (since you might be able to read the file, but not able to check the permissions). Even Windows' error message says you either don't have permission or it's being used by another process.

You can use WMI CIM_DataFile class to query InUseCount for a specified data file.

If you're looking for a programmatical equivalent to lsof utility in Linux, to find out all open files by a given process, you could try using Win32_Process WMI class through System.Management namespace. 进程的所有打开文件,您可以尝试通过System.Management命名空间使用Win32_Process WMI类。 You could issue a WMI query to look up the file name in all open files being used by all local processes too see if it's there or not. Alternatively, you could P/Invoke and use NtQuerySystemInformation API directly to accomplish the same task.

This will do. FileShare.None as mentioned in MSDN :

None : Declines sharing of the current file. Any request to open the file (by this process or another process) will fail until the file is closed.

File.Open(name, FileMode.Open, FileAccess.Read, FileShare.None);

EDIT : Remember to wrap in a Try/Catch block, and using FileShare.None actually means you want to open the file exclusively.

bool CanReadAndWrite(string path)
{
    var perm = new System.Security.Permissions.FileIOPermission(
         System.Security.Permissions.FileIOPermissionAccess.Write |
         System.Security.Permissions.FileIOPermissionAccess.Read,
         path);
    try
    {
         perm.Demand();
         return true;
    }
    catch 
    {
         return false;
    }
}

Checks to see if you can read and write to a file.

Use System.IO.File.OpenWrite(path). Surround it in a try/catch block, and if it is already open for writing somewhere else, you will get a System.UnauthorizedAccessException.

The following syntax will help:

FileStream s2 = new FileStream(name, FileMode.Open, FileAccess.Read, FileShare.Read);

In general, you should always avoid relying on file accessibility checks. The reason is that it might be, and then it may change just a couple of cycles before you access it.

Instead, just try to open it and see if you have any errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM