从CSV C#中删除空白行 [英] Remove Blank rows from csv c#

查看:486
本文介绍了从CSV C#中删除空白行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

id希望在下图中删除/跳过这些突出显示的行,因此它们不再出现在csv文件中.正如您在下面看到的那样,因为这两行是空的,所以将这两行显示为(,,).

id like to remove/skip these highlighted rows in the image below so they would not appear on the csv file anymore. as you can see below it display the two rows as (,,) because the rows are empty.

您也可以在代码中看到我尝试在两种方法中使用string.Empty,但似乎没有任何进展,因为我不确定如何做到这一点.

as you can also see in the code i tried to used string.Empty in both method but did not seem to get anywhere as i am not really sure on how to do this.

任何建议

 class Program
{
    static void Main(string[] args)
    {
        var filePath = Path.Combine(Directory.GetCurrentDirectory(), "Santander .csv");
        var fileContents = ReadFile(filePath);
        foreach (var line in fileContents)
        {
            if (!line.Equals(String.Empty))
                continue;
            Console.WriteLine(line);
        }

        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
    } 

    public static IList<string> ReadFile(string fileName)
    {
        var results = new List<string>();
        var target = File.ReadAllLines(fileName)
                 .ToList();
        foreach (string currentLine in target)
        {
            if( !currentLine.Equals( String.Empty ) )
            {
                continue;
            }


        }

         File.WriteAllLines(fileName, target);

        return results.ToList();

推荐答案

您可以通过用,拆分每行并比较前两列来过滤行.

You could filter the rows by splitting each row with , and comparing first two columns.

var nonEmptyLines = File.ReadAllLines(fileName)
                        .Where(x=> !x.Split(',')
                                     .Take(2)
                                     .Any(cell=> string.IsNullOrWhiteSpace(cell))
                                     // use `All` if you want to ignore only if both columns are empty.  
                         ).ToList();

File.WriteAllLines(fileName, nonEmptyLines);  

这篇关于从CSV C#中删除空白行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆