从CSV文件中删除指定的文本

时间:2019-03-08 09:45:06

标签: c# csv foreach

这是我第一次尝试这样做,我不知道自己是否正确。

基本上我想从包含特定关键字的CSV文件中删除文本,但是我不知道如何删除该行。

  static void Main(string[] args)
    {
        var searchItem = "running";

        var lines = File.ReadLines("C://Users//Pete//Desktop//testdata.csv");

        foreach (string line in lines)
        {
            if (line.Contains(searchItem))
            {
                //Remove line here?
            }
        }
    }

4 个答案:

答案 0 :(得分:1)

请尝试删除一个或几个单词。

static void sd(string[] args)
{
    string contents = File.ReadAllText("C://Users//Pete//Desktop//testdata.csv");

    string output = contents.Replace("running", string.Empty).Replace("replaceThis", string.Empty).Replace("replaceThisToo", string.Empty);
    //string output = contents.Replace("a", "b").Replace("b", "c").Replace("c", "d");
}

要删除多个字符串,您可以使用此...

static void Main(string[] args)
{
    string[] removeTheseWords = { "aaa", "bbb", "ccc" };

    string contents = File.ReadAllText("C://Users//Pete//Desktop//testdata.csv");
    string output = string.Empty;

    foreach (string value in removeTheseWords)
    {
        output = contents.Replace(value, string.Empty);
    }
}

更多信息:https://docs.microsoft.com/en-us/dotnet/api/system.string.replace

答案 1 :(得分:0)

您无需删除行,只需跳过包含搜索字词的行

foreach (string line in lines)
{
    if (!line.Contains(searchItem))  //<= Notice here I added exclamation mark (!)
    {
        //Do your work when line does not contains search term
    }
    else
    {
        //Do something if line contains search term
    }
}

的替代方案是在循环前过滤不包含搜索字词的行,例如

lines = lines.Where(line => !line.Contains(searchItem));

foreach (string line in lines)
{
    //Here are those line that does not contain search term                
}

如果您的搜索词包含多个用逗号(,)分隔的单词,则可以跳过这些行

lines = lines.Where(line => searchItem.Split(',').All(term => !line.Contains(term)));

答案 2 :(得分:0)

如果您使用的是foreach并通过称为集合修改后的异常的行将其从行中删除,请使用for

for(int i=lines.Count - 1; i > -1; i--)
{
 if (lines[i].Contains(searchItem))
  {
    lines.RemoveAt(i);
  }
}

答案 3 :(得分:0)

要删除整行的简单方法:

    var searchItem = "running";
    var pathToYourFile = @"C://Users//Pete//Desktop//testdata.csv";
    var lines = File.ReadAllLines(pathToYourFile);
    lines = lines.Where(line => !line.Contains(searchItem)).ToArray();
    File.WriteAllLines(pathToYourFile, lines);

对于多个搜索项:

    var searchItems = "running;walking;waiting;any";
    var pathToYourFile = @"..\..\items.csv";
    var lines = File.ReadAllLines(pathToYourFile);
    // split with your separator, actually is ';' character
    foreach(var searchItem in searchItems.Split(';'))
        lines = lines.Where(line =>!line.Contains(searchItem)).ToArray();

    File.WriteAllLines(pathToYourFile, lines);