2016-12-30 42 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(output); string contentsToRead = File.ReadAllText(output); sr.Close(); string contentsToWrite = replay.ReplayBuild +「,」+ replay.Map; if(!contentsToRead.Contains(contentsToWrite)) TextWriter twt = new StreamWriter(output); twt.WriteLine(contentsToWrite); twt.Close(); } 不是隻有一行數據被寫入表單,但我實際上不明白爲什麼。任何建議? –

+0

您可以使用您所做的更改更新問題,它在評論中不可讀。謝謝。 –

0

我建議使用File.ReadLines以及File.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); 
相關問題