2016-06-23 9 views
1

私はVisual C# applicationを作成していますが、その機能の一部は、ディレクトリに表示された.gzファイルを抽出することです。 .gzファイルは、コマンドライン引数が実行されると、指定されたディレクトリに表示されます。ファイルがディレクトリに存在するのを待っていますC#

残念ながら、「このファイルが見つかりません」という行に沿って何かが表示されるというエラーが表示されます。これは、.gzファイルをあまりにも速く抽出する行を読み取る理由によるものです。

つまり、コマンドライン引数が実行される前に.gzファイルを実行しようとしていて、実際にファイルをディレクトリに配置しています。

私のプログラムが次の行を読み続ける前に、ファイルがディレクトリに現れるのを待つ方法を見つけたいと思います。

以下は私のコードですが、何か助けていただければ幸いです!ありがとう!

else if (ddlDateType.Text == "Monthly" || ddlDateType.Text == "") 
{ 
    //Check if Monthly date entered is valid 
    if (DateTime.TryParseExact(txtDate.Text, MonthlyFormat, null, 
     System.Globalization.DateTimeStyles.None, out Test) != true) 
    { 
     MessageBox.Show("Enter a valid date.\nFormat: yyyyMM"); 
    } 
    else 
    { 
     //Method that executes an arugment into the command prompt 
     ExecuteCommand(); 

     //Method that extracts the file after it has already appeared in the directory 
     ExtractFile(); 

     /* 
     Goal is to wait for the file to appear in the directory before it executes 
     the ExtractFile() method. 
     */ 

    } 
} 
+0

私の最初の考えは、while(!File.Exists(theFile)){System.Threading.Thread.Sleep(1000);を実行することです。 } ' – Quantic

答えて

4

FileSystemWatcherを使用できます。 https://msdn.microsoft.com/it-it/library/system.io.filesystemwatcher(v=vs.110).aspx

この例では、ファイルが監視対象フォルダに追加されるたびにコールバックOnChangedが呼び出されます。

[PermissionSet(SecurityAction.Demand, Name="FullTrust")] 
    public static void RunWathcer() 
    { 

     // Create a new FileSystemWatcher and set its properties. 
     FileSystemWatcher watcher = new FileSystemWatcher(); 

     watcher.Path = "PATH TO WATCH GOES HERE!!"; 

     /* Watch for changes in LastAccess and LastWrite times, and 
      the renaming of files or directories. */ 
     watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; 

     watcher.Filter = "*.*"; 

     watcher.Created += new FileSystemEventHandler(OnChanged); 
     watcher.EnableRaisingEvents = true; 
    } 

    // Define the event handlers. 
    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); 
    } 
} 
+0

悪魔の主唱者を演奏する:必要なファイル以外のものがこのディレクトリパスで変更されたらどうなりますか?それは失敗しないでしょうか? –

+1

明らかに、期待されるファイル名などをフィルタリングする必要があります。私は可能な解決策を提案していますが、私はすべてのプログラムが表示されないので、私は予測できません:-) –

+2

このFileSystemWatcherクラスが存在することはわかりませんでした。私はこれが役に立つと思う。 @Gary watcher.Filterは、名前が動的であれば特定のファイルやファイル拡張子を探すように設定することができます。 – JaredStroeb

関連する問題