2017-07-10 21 views
0

質問があります。フォルダを監視するFileWatcherを作成しています。削除したファイルを別の場所からコピーするメソッドを作成しようとしています。FileSystemWatcher - 削除時にファイルをコピーする

これは、FileSystemEventHandlerを使用すると可能ですか?

最後に、FileSystemWatcherを使用してフォルダを変更することはできますか?

ありがとうございました。

あなたのコードは次の線に沿って何かする必要があります
+0

あなたがに似たものを実装しようとしています。https([Windowsがファイルを保護]:// support.microsoft.com/en-us/help/222193/description-of-the-windows-file-protection-feature)?もしそうなら、私はあなたがWindowsでなくてもそれを行うことができるとは確信していません。そうでない場合、私はあなたのシナリオをはっきりと理解していません。 –

+0

私は3つのファイルを持つフォルダを持っている、私はフォルダを監視したい。 ファイルの1つが削除された場合、私はファイルウォッチャーが同じファイルを他のフォルダーからコピーしたいと思っています。 –

+0

はい、可能です。 [docs](https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.deleted.aspx)を見ましたか? – Blorgbeard

答えて

0

using System.IO; 

//... 

const string SourceDirectory = @"\\myServer\share\originalFiles"; 
private static void OnDeleted (object source, FileSystemEventArgs e) 
{ 

    //this will help prove if the fsw is being triggered/whether the error's in your copy file piece or due to the trigger not firing 
    Debug.WriteLine(e.FullPath); 
    Debug.WriteLine(e.ChangeType); 

    var filename = e.Name; //NB: Returns path relative to the monitored folder; e.g. if monitoring "c:\demo" and file "c:\demo\something\file.txt" is changed, would return "something\file.txt" 
    //var filename = Path.GetFilename(e.FullPath); //if you don't want the above behaviour, given the same scenario this would return "file.txt" instead 
    var sourceFilename = Path.Combine(SourceDirectory, filename); 

    /* not sure if this is required: see https://github.com/Microsoft/dotnet/issues/437 
    while (File.Exists(e.FullPath)) { //just in case the delete operation is still in progress when this code's triggered. 
     Threading.Thread.Sleep(500); 
    } 
    */ 

    File.Copy(sourceFilename, e.FullPath); 
} 

//... 

const string MonitoredDirectory = @"\\myServer\share\watchedFiles\"; 
public static void Main(string[] args) { 
    FileSystemWatcher fsw = new FileSystemWatcher(); 
    fsw.Path = MonitoredDirectory; 
    fsw.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; 
    //fsw.Filter = "*.xml"; //add something like this if you want to filter on certain file extensions/that sort of thing 
    fsw.OnDeleted += new FileSystemEventHandler(OnDeleted); 
    fsw.EnableRaisingEvents = true; 
    Console.WriteLine("This monitor will now run until you press 'x' (i.e. as we need to keep the program running to keep the fsw in operation)"); 
    while(Console.Read() != 'x'); 
} 

(上記未テストです)

+0

これは機能しますか?このイベントが発生する前にファイルが削除されていませんか?上記のように@ErnodeWeerd –

+0

、これはテストされていません。しかしそれは問題ではありません。削除されたファイルをコピーするのではなく、 "テンプレート"を取り出して、削除したファイルの元の場所にコピーします。潜在的な問題は、コピーが呼び出された時点までにファイルが完全に削除されていない可能性のある競合状態に関連しています。そのためにwhile(File.Exists(e.FullPath))ループのコメントを解除する必要がありますが、削除とコードの実行の間にファイルが再作成されるという無限ループにつながる可能性があります。そのようなシナリオを改善/保護するためにはタイムアウトが必要です – JohnLBevan

関連する問題