搜索字符串,如果不匹配则删除行

时间:2013-08-13 13:23:05

标签: c# csv file-io

我正在寻找打开文本文件的代码,然后逐行读取文本文件,如果文本文件中的行(每行将存储大约5个值)不包含某个值,例如“hart”那么我想删掉那条线。我正在使用c#和vs2012,有谁能告诉我如何做到这一点?正在读取的文件是csv文件。我这里没有代码示例,因为我当前的代码不起作用,我觉得givin示例只会导致更多的混乱,而不是要求某人向我展示一个干净的新方法。

我添加了我目前拥有的代码,它将所有数据添加到文本文件中,但我需要弄清楚的代码是获取这些结果并过滤它们

     foreach (DataRow dr in this.CalcDataSet.Items)
        {

           foreach (object field in dr.ItemArray)
                {
                    str.Append(field.ToString() + ",");
                }


            str.Replace(",", "\n", str.Length - 1, 1);
        }


        try
      {
            System.IO.File.WriteAllText(Filepath, str.ToString());

        }
        catch (Exception ex)
        {
            MessageBox.Show("Write Error :" + ex.Message);
        }

        var lines = System.IO.File.ReadAllLines(Filepath).ToList();
        var acceptedLines = new List<string>();
        foreach (var line in lines)
            if (Matches(line))
                acceptedLines.Add(line);

        System.IO.File.WriteAllLines(Filepath, acceptedLines);
    }

    private bool Matches(string s)
    {
        if (s == cmbClientList.SelectedText.ToString())
        {
            return true;
        }

        else  return false;
    }

3 个答案:

答案 0 :(得分:1)

使用TextFieldParser类打开并读取文件,并将值拆分为数组。然后,您可以检查每一行上的每个项目,看它是否包含您想要的值。

如果该行包含该值,则将该行写入新文件。如果它不包含该值,则不要写入新文件。

完成后,关闭输入和输出文件。然后删除原始输入文件并重命名输出文件。

您无法轻松地就地阅读和修改文本文件。

另一种选择是使用TextFieldParser读取并写入内存中的流。最后,从内存流写回原始文件。如果文件足够小以适合内存,这将起作用。

答案 1 :(得分:1)

这基本上可以做你想要的:

var lines = System.IO.File.ReadAllLines("somefile.csv");
var acceptedLines = new List<string>();
foreach (var line in lines)
    if (Matches(line))
        acceptedLines.Add(line);
System.IO.File.WriteAllLines("output.csv", acceptedLines);


private bool Matches(string s) {
    // Whatever you want, return true to include the line, false to exclude)
}

答案 2 :(得分:0)

你可以这样做

string[] lines  = File.ReadAllLines("yourfile.csv");
List<string> linesToWrite = new List<string>();
int currentCount = 0;

foreach(string s in lines)
{     
  if(s.Contains("YourKeyValue"))
     linesToWrite.Add(s);  
}
File.WriteAllLines("yourfile.csv", linesToWrite );