代码之家  ›  专栏  ›  技术社区  ›  adopilot

如何在将两个TXT文件发送到SQL之前进行比较

  •  0
  • adopilot  · 技术社区  · 15 年前

    0000199991
    0000199321
    0000132913
    0000232318
    0000312898
    

    在第二次从设备获取数据的调用中,它将再次返回所有(上一次和下一次捕获的记录)类似的内容

    0000199991
    0000199321
    0000132913
    0000232318
    0000312898
    9992129990
    8782999022
    2323423456
    

    但这次我只想计算并传递在第一次插入之后添加的槽数据。 我正在尝试使用C#和visualstudio2008制作winforms应用程序

    3 回复  |  直到 15 年前
        1
  •  3
  •   SLaks    15 年前

    您可以使用LINQ:

    string[] addedLines = File.ReadAllLines(secondPath)
                              .Except(File.ReadAllLines(firstPath))
                              .ToArray();
    

    请注意,对于大文件,这将很慢。

    对于大文件,替换 ReadAllLines 使用以下方法:(在.NET4中,可以使用 File.ReadLines

    static IEnumerable<string> EnumerateLines(string path) {
        using(var reader = File.OpenText(path)) {
            string line;
            while(null != (line = reader.ReadLine())
                yield return line;
        }
    }
    
        2
  •  1
  •   soniiic    15 年前

    这对你有用吗?

    string dataAddedAfterFirstInsert = secondString.SubString(firstString.Length, secondString.Length)
    
        3
  •  1
  •   Chris Taylor    15 年前

    一种方法是,每次收到文件时都要记住文件大小,然后在得到新文件时,可以立即将文件指针移动到文件中与上一个文件结尾相对应的位置,并从该位置开始读取。

    这是这个想法的大致轮廓

      long lastPosition = GetLastFilePositionFromDatabase();
      using (FileStream fs = new FileStream(...))
      {
        // Seek to the last position, this is zero the first time
        fs.Seek(lastFilePosition, SeekOrigin.Begin);
    
        // Process your file from the current position
        ProcessFile(fs);
    
        // Once you reach the end of the file, save this position so 
        // for use with the next file
        SaveLastFilePositionToDatabase(fs.Position);
      }