2016-12-30 43 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); 
相关问题