【问题标题】:Skip first 4 lines in txt file then split the rest and read it跳过 txt 文件中的前 4 行,然后拆分其余行并阅读
【发布时间】:2017-06-10 14:19:44
【问题描述】:

这是我的代码,首先我想跳过前 4 个字母并拆分其余字母并读取它以根据 txt 文件更新我的数据库。

StreamReader sr = null;
try
{
    FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
    sr = new StreamReader(fs);
    string lines = sr.ReadLine();

    while (!sr.EndOfStream)
    {
        string[] words = lines.Split(' ');
        string ReservationNumber = words[0];
        double deposit = Convert.ToDouble((words[1]));

        if (GetCustomer(ReservationNumber).Customer_Res_Number == ReservationNumber)
        {
            UpdateDeposit(ReservationNumber, deposit);
        }
        lines = sr.ReadLine();
    }
}

【问题讨论】:

    标签: c# database split


    【解决方案1】:

    为什么不使用File 类和Linq 而不是Streams 和Readers?对于 Linq,很容易跳过 4 顶部文件的行 - Skip(4)

    跳过4顶部(文件的标题?):

    // Data (lines) to process
    var lines = File
      .ReadLines(filename)
      .Skip(4)                            // <- Skip first 4 lines (file's caption?)
      .Select(line => line.Split(' '))
      .Select(words => new {
         ReservationNumber = words[0],
         deposit = Convert.ToDouble(words[1]), 
        })
      .Where(rec => GetCustomer(rec.ReservationNumber).Customer_Res_Number ==
                    rec.ReservationNumber);  
    
    // Data Processing
    foreach (var item in lines)
      UpdateDeposit(item.ReservationNumber, item.deposit);
    

    如果您想从第一行跳过第一个4 字符(校验和或类似的?):

    var lines = File
      .ReadLines(filename)
      .Select((line, index) => index == 0 
         ? line.Substring(4) // <- Skip 4 first characters from the 1st line
         : line) 
      .Select(line => line.Split(' '))
    ...
    

    最后,如果你想从 each 行中跳过4 characters

    var lines = File
      .ReadLines(filename)
      .Select(line => line.Substring(4)) // <- Skip 4 fisrt characters from each line
      .Select(line => line.Split(' '))
    ...
    

    【讨论】:

      【解决方案2】:

      也许……?

      while (!sr.EndOfStream)
      {
          string line = sr.ReadLine();
          string newline = line.Substring(3);
          ...
      }
      

      【讨论】:

      • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
      • 这个是跳过字母不换行,但是谢谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-19
      • 2010-09-16
      • 1970-01-01
      • 2013-05-11
      • 1970-01-01
      • 2023-03-25
      相关资源
      最近更新 更多