2016-11-07 95 views
-1

我有一个用例,我需要检测是否使ReadOnly文件可写。我试过使用FileSystemWatcher,但它不告诉我文件的哪个属性已经改变。

C# - 监视是否属性只读任何文件已更改

// Create a new FileSystemWatcher and set its properties. 
    FileSystemWatcher watcher = new FileSystemWatcher(); 
    watcher.Path = args[1]; 
    /* Watch for changes in Attribute (In this case only Readonly attribute). */ 
    watcher.NotifyFilter = NotifyFilters.Attributes; 

    private static void OnChanged(object source, FileSystemEventArgs e) 
    { 
     // Specify what is done when a file is changed, created, or deleted. 
     Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType); 
    } 

我不知道哪些文件是只读的,哪些不是。所以我不能只检查Changed事件上文件的ReadOnly属性。

+2

那么,如果你正在看一个只读文件,并得到一个通知,它已经改变了,你不能只是检查属性呢? –

+0

你需要注意System.IO.NotifyFilters。 虽然,看到看到相关的其他答案哪一个适合你的代码 https://msdn.microsoft.com/en-us/library/system.io.notifyfilters(v=vs.110).aspx – celerno

+0

@PeterDuniho你可以请重新打开这个问题。我做了编辑。 – Peaked

回答

1

结帐System.IO.FileInfo.IsReadOnly。基本上你可以通过在OnChanged事件处理程序中执行以下操作来判断它是否可写。这是基于该文件最初是只读的假设。

// Define the event handlers. 
private static void OnChanged(object source, FileSystemEventArgs e) 
{ 
    // Specify what is done when a file is changed, created, or deleted. 
    if(!System.IO.FileInfo.IsReadOnly) changedToWritable = true; 

} 

注意https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(v=vs.110).aspx指示FileSystemWatcher的OnChanged报告文件属性的更改。

+0

我不知道受监视目录中的哪些文件是只读的 – Peaked

相关问题