2017-07-17 16 views
1

私はそれが混乱しているコードを整理しようとしています!この時点での最初の、そして私の最大の問題は、私のStreamWritersまたはStreamReaderの1つが開いたままになっていることです。 this linkを使用して、自分のコードを整理しようとしています。しかし、私の問題は、私は、私はそれを閉じるべき場所を確認していないということです。StreamWriterとStreamReaderを閉じる最善の方法

私のコードは次のとおりです。

public static void ProcessFile(string[] ProcessFile, int id_customer, string directoryinprocess) 
{ 
    StreamWriter Writer = null, Writer2 = null, Writer3 = null; 

    foreach (string filename in ProcessFile) 
    { 

     // Used for the output name of the file 
     var dir = Path.GetDirectoryName(filename); 
     var fileName = Path.GetFileNameWithoutExtension(filename); 
     var ext = Path.GetExtension(filename); 
     var folderbefore = Path.GetFullPath(Path.Combine(dir, @"..\")); 
     int rowCount = 0; 
     string path_body_out = ""; 
     string outputname = folderbefore + "output_temp\\" + fileName; 

     if (filename.Contains("RO_")) 
     { 
      Writer = new StreamWriter(dir + "\\" + "output_temp\\" + fileName + "_hd_intermediate" + ext) { AutoFlush = true }; 
      Writer2 = new StreamWriter(dir + "\\" + "output_temp\\" + fileName + "_body_out" + ext) { AutoFlush = true }; 
      path_body_out = dir + "\\" + "output_temp\\" + fileName + "_hd_intermediate" + ext; 
     } // end of if 
     else 
     { 
      Writer3 = new StreamWriter(dir + "\\" + "output_temp\\" + fileName + "_out" + ext) { AutoFlush = true }; 
     } // end of else 

     using (StreamReader Reader = new StreamReader(@filename)) 
     { 
      while (!Reader.EndOfStream) 
      { 
       string inputLine = string.Empty; 
       inputLine = Reader.ReadLine(); 

       rowCount++; 

       if (filename.Contains("RO_")) 
       { 
        if (rowCount <= 4) 
        { 
          Writer.WriteLine(inputLine); 
        } 
        if (rowCount >= 5) 
        { 
         Writer2.WriteLine(inputLine); 
        } 
       } 
       else 
       { 
        { Writer3.WriteLine(inputLine); } 
       } 

      } // end of the while 
     } // end of using Stremreader 


     if (path_body_out.Contains("_hd_intermediate")) 
     { 
      ManipulateHeaderFilesTypeRo(dir, path_body_out); 
     } 
     else 
     { } 
    } // end of the foreach 


    string[] extensions = { "_fv", "_body", "_out" }; 

    string[] fileEntriesout = System.IO.Directory.EnumerateFiles(directoryinprocess, "*.csv", System.IO.SearchOption.AllDirectories) 
    .Where(file => extensions.Any(ex => Path.GetFileNameWithoutExtension(file).EndsWith(ex))) 
     .ToArray(); 


    foreach (string filenameout in fileEntriesout) 
    { 
     string destinytablename = null; 

     if (filenameout.Contains("_hd_intermediate_fv")) 
     { destinytablename = "TBL_DATA_TYPE_RO_HEADER"; } 
     else if (filenameout.Contains("_body_out")) 
     { destinytablename = "TBL_DATA_TYPE_RO_BODY"; } 
     else 
     { destinytablename = "TBL_DATA_TYPE_LOAD"; } 

     string id_file = Get_id_file(filenameout, id_customer); 

     DataTable csvFileData = GetDataTabletFromCSVFile(filenameout, id_file); 

     InsertDataIntoSQLServerUsingSQLBulkCopy(csvFileData, destinytablename); 

    } // end of the foreach 

    //} // end of the foreach 

} // end of ProcessFile 
  • 質問: はどのように私はパーツを閉じる必要があります。

    if (filename.Contains("RO_")) 
        { 
         Writer = new StreamWriter(dir + "\\" + "output_temp\\" + fileName + "_hd_intermediate" + ext) { AutoFlush = true }; 
         Writer2 = new StreamWriter(dir + "\\" + "output_temp\\" + fileName + "_body_out" + ext) { AutoFlush = true }; 
         path_body_out = dir + "\\" + "output_temp\\" + fileName + "_hd_intermediate" + ext; 
        } // end of if 
        else 
        { 
         Writer3 = new StreamWriter(dir + "\\" + "output_temp\\" + fileName + "_out" + ext) { AutoFlush = true }; 
        } // end of else 
    
        using (StreamReader Reader = new StreamReader(@filename)) 
        { 
         while (!Reader.EndOfStream) 
         { 
          string inputLine = string.Empty; 
          inputLine = Reader.ReadLine(); 
    
          rowCount++; 
    
          if (filename.Contains("RO_")) 
          { 
           if (rowCount <= 4) 
           { 
             Writer.WriteLine(inputLine); 
           } 
           if (rowCount >= 5) 
           { 
            Writer2.WriteLine(inputLine); 
           } 
          } 
          else 
          { 
           { Writer3.WriteLine(inputLine); } 
    

ここで閉じる必要がありますか?

 if (filename.Contains("RO_")) 
     { 
      Writer = new StreamWriter(dir + "\\" + "output_temp\\" + fileName + "_hd_intermediate" + ext) { AutoFlush = true }; 
      Writer2 = new StreamWriter(dir + "\\" + "output_temp\\" + fileName + "_body_out" + ext) { AutoFlush = true }; 
      path_body_out = dir + "\\" + "output_temp\\" + fileName + "_hd_intermediate" + ext; 
     } // end of if 
     else 
     { 
      Writer3 = new StreamWriter(dir + "\\" + "output_temp\\" + fileName + "_out" + ext) { AutoFlush = true }; 
     } // end of else 

ここですか?すべてのStreamWriterインスタンスがusing()に包まれることができるようにあなたは、このコードを再編成することができない場合

   if (filename.Contains("RO_")) 
       { 
        if (rowCount <= 4) 
        { 
          Writer.WriteLine(inputLine); 
        } 
        if (rowCount >= 5) 
        { 
         Writer2.WriteLine(inputLine); 
        } 
       } 
       else 
       { 
        { Writer3.WriteLine(inputLine); } 
       } 

答えて

5

は、その後、おそらくあなたは、このような何かを行うことができます。

StreamWriter Writer = null, Writer2 = null, Writer3 = null; 

try 
{ 
    // your existing code 
} 
catch 
{ 
    // Handle 
} 
finally 
{ 
    if (Writer != null) 
     Writer.Close(); 
    if (Writer2 != null) 
     Writer2.Close(); 
    if (Writer3 != null) 
     Writer3.Close(); 
} 

これは確実に関係なく、どのようなエラーことあなたの作家が閉鎖されることがtry内で起こります。

私の意見では、条件付きでインスタンス化するオブジェクトはにおいであり、filename.Contains("RO_")に基づいて異なる実装を行うべきです。戦略パターンを使用し、異なるファイル・プロセッサー・インターフェースの実装を持ち、ファイル名に基づいて正しいものを選択することができます。各実装は、必要な場所に書き込む方法しか知りません。これにより、各ライターの周囲にusing()を正しく使用することができます。

+0

うん、それは間違いない!今、それが働いている、私はこの混乱を改善するために働く、今私は今これが問題です。ありがとうございました。 –

1

使い捨てオブジェクトを使用している場合は、usingブロックを使用してください。しかし、あなたは条件付きで使い捨てのオブジェクトを導入しているので、try-finallyブロックの使用が最善の策だと思います。

使い捨てオブジェクトを宣言し、tryブロックの外側でnullに初期化します。

tryブロックの内部にあるインスタンスに使い捨てオブジェクトを初期化します。使い捨てオブジェクトを作成したら、try-blockのどこにでもこの参照を変更しないように注意してください。

また、tryブロックの中で、使い捨てオブジェクトで行う必要があるすべてを行います。

tryブロックの後にfinallyブロックを作成します(キャッチブロックはオプションですが、このメソッドがそのジョブを実行するにはfinallyブロックが必要です)。finallyブロックの中で、使い捨てオブジェクトはnullではありません。それらがnullでない場合は、それらを閉じてnullにします。

StreamWriter writer = null; 

try { 
    if (condA) { 
     writer = new StreamWriter("filePath1"); 
    } else if (condB) { 
     writer = new StreamWriter("filePath2"); 
    } else { 
     writer = new StreamWriter("filePath3"); 
    } 

    // do things with writer 

} catch (Exception ex) { 

} finally { 
    if (writer != null) { 
     writer.close(); 
     writer = null; 
    } 
} 
+0

このオプションでも動作します!ありがとうございました。申し訳ありませんが、私は両方の仕事、最初の答えを修正したとタグ付け!ありがとうございました。 –

関連する問題