2016-04-07 11 views
0

.pgpファイルを復号化して別の場所に移動しようとしています。私はこれを調べてarticleとそれに応じてコードします。私のコードでは、100秒ごとに特定の場所にチェックするアプリケーションを開発しています。ファイルがあれば、それは復号化して移動します。しかし、私はこの例外を取得していますThe process cannot access the file 'c:\file.pgp' because it is being used by another process.フォルダからpgpファイルを解読して移動する - c#

ここで私はその記事からコピーしたクラスを呼び出しています。

private static void OnTimedEvent(object source, ElapsedEventArgs e) 
    { 
     //Do the stuff you want to be done every hour; 
     string sourcePath = @"files location"; 
     string archivePath = @"move original file after decrypting location"; 
     string targetPath = @"decrypted file location"; 
     string pubkeyPath = @"public key location\PGPPublicKey.txt"; 
     string privkeyPath = @"private key location\PGPPrivateKey.txt"; 

     string fileName = ""; 
     string destFile = ""; 

     if (System.IO.Directory.Exists(sourcePath)) 
     { 
      string[] files = System.IO.Directory.GetFiles(sourcePath); 

      // Copy the files and overwrite destination files if they already exist. 
      foreach (string s in files) 
      { 
       PGPDecrypt test = new PGPDecrypt(s, 
             privkeyPath, 
             "password", 
             targetPath + "decrypted.txt", 
             pubkeyPath); 
       FileStream fs = File.Open(s, FileMode.Open); 
       test.decrypt(fs, targetPath + "decrypted.txt"); 

       // Use static Path methods to extract only the file name from the path. 
       fileName = System.IO.Path.GetFileName(s); 
       destFile = System.IO.Path.Combine(archivePath, fileName); 
       System.IO.File.Move(s, archivePath); 
      } 
     }   
    } 

答えて

0

ここで、エラーが発生しています。移動中にエラーが発生した場合は、ファイルストリームが近くにない可能性があります。復号化後、移動前にfs.Close()でファイルストリームを閉じます。

+0

私はこのライン 'のFileStream fsの= File.Open(S、FileMode.Open)上の例外を取得していますの終わりに

fs.Close(); 

を加える;' ' –

0

あなたが持っている問題は、ファイルが閉じられていないことが原因だと思います。foreachループでループすると、おそらく最初の反復が機能します。しかし、次回は決して閉じられなかったので、まだ使用されています。

てみforeachループ

+0

のFS .Close() 'は、この例外を' FileStream fs = File.Open(s、FileMode.Open);で取得していたため動作しませんでした; ' –

+0

' fs.Closeの前に 'FileClose();' (); ' –

+0

前に閉じるファイルがありません –