2016-12-30 9 views
-2

CSVファイルに正確な文字列が既に存在しない場合は、文字列としてCSVファイルに行を書き込もうとしています。行が存在するかどうかをチェックしないと、私のコードはうまく動作します。C# - 行が存在しない場合に行を書き込む

私の現在のコードは以下のように見え、ちょうどうまくいかないようです。

string output = @"output.csv"; 
TextWriter tw = new StreamWriter(output); 

foreach (var player in replay.Players.OrderByDescending(i => i.IsWinner)) 
{ 
    using (StreamReader sr = new StreamReader(output)) 
    { 
     string contentsToRead = File.ReadAllText(output); 
     string contentsToWrite = replay.ReplayBuild + "," + replay.Map; 
     if (!contentsToRead.Contains(contentsToWrite)) 
      tw.WriteLine(contentsToWrite); 
     sr.Close(); 
    } 
} 
tw.Close(); 

私はC#とプログラミング一般に全く新しいです。私が取り組んでいるファイルの主な仕事は私のものではありません。元々はhttps://github.com/barrett777/Heroes.ReplayParser

です。私がStreamReaderをコメントアウトしてWriteラインのみを使用すると、少なくとも私が理解する限り、完全に機能します。

私はどのように改善することができますか、どんな種類のヘルプやヒントもありがとうございます。前もって感謝します。

答えて

1

ファイルを開く前にファイルの内容を読むようにしてください(new StreamWriter(output)行の前)。

+0

限り、私はあなたのリプレイにリーダーを閉じる前に作家の開口部を理解して問題を引き起こしている、そうですか? 書き換えはまだ動作しません。私は以下を追加しました: TextReader sr = new StreamReader(出力); 文字列contentsToRead = File.ReadAllText(出力); sr.Close(); 文字列contentsToWrite = replay.ReplayBuild + "、" + replay.Map; if(!contentsToRead.Contains(contentsToWrite)) { TextWriter twt = new StreamWriter(出力); twt.WriteLine(contentsToWrite); twt.Close(); } 1行のデータだけがシートに書き込まれるわけではありませんが、実際はその理由を理解できません。なにか提案を? –

+0

あなたが行った変更で質問を更新できますか?それはコメントではあまり読みにくくありません。ありがとう。 –

0

File.ReadLinesFile.AppendAllLinesを使用することをお勧めします。ためには(時間がかかることが)ラインでファイル 行を更新していないが、一度に、私は、LINQのをお勧めします。

string output = @"output.csv"; 
... 

// Hash set is effcient - O(N) - for testing if line exists or not 
HashSet<String> existingLines = new HashSet<String>(File 
    .ReadLines(output)); 

//TODO: please, check this selection (I'm not sure in ReplayBuild and Map attributes) 
var toAppend = replay 
    .Players 
    .Select(player => new { 
    toWrite = string.Join(",", player.ReplayBuild, player.Map), 
    isWinner = player.IsWinner }) 
    .Where(item => existingLines.Contains(item.toWrite)) 
    .OrderByDescending(item => item.isWinner) 
    .Select(item => item.toWrite) 
    .ToList(); // since we're writing into the same file, we have to materialize 

// Do we have anything to write? 
if (toAppend.Any()) 
    File.AppendAllLines(output, toAppend); 
関連する問題