C#基于一个共同的ID合并两个文本文件

时间:2019-03-17 12:09:25

标签: c#

我有两个如下所示的文本文件。我有一些常见的东西,例如ID_1 deg&End,我需要将它们之间的数据复制并合并到一个新文件中。

第一个文件:

ID_1  deg
12212  -45.22 -22.66
155566 -22.02  66.55
222312  22.56 -33.54
End
ID_2  deg
12232   35.22 -62.16
355526 -32.02 -26.55
62665   21.56 -2.53
End

第二个文件:

ID_1  deg
22332  -35.22 -52.66
155566  -6.02  33.55
222312 -62.56 -3.50
End
ID_2  deg
52232   23.22 -61.16
955526 -33.02 -66.55
12665  -33.56  -1.53
End

输出(合并后)文件:

ID_1  deg
12212  -45.22 -22.66
155566 -22.02  66.55
222312  22.56 -33.54
12232   35.22 -62.16
355526 -32.02 -26.55
62665   21.56  -2.53
End
ID_2  deg
12232   35.22 -62.16
355526 -32.02 -26.55
62665    21.56 -2.53
52232   23.22 -61.16
955526 -33.02 -66.55
12665  -33.56  -1.53
End

我想通过公共ID_1(名称)合并两个文本文件,并以考虑ID_“”之间的重复数据结束。 如果对上述情况至少有一些了解,我对编程非常陌生。

1 个答案:

答案 0 :(得分:0)

Here's one way, since you know what the data looks like:

string input_file1 = "input_file1_path_here";
string input_file2 = "input_file2_path_here";
string outputfile = "your_output_file_path_here";
int start = 0;
string lst1 = string.Empty;
string lst1b = string.Empty;
string lst2 = string.Empty;
string lst2b = string.Empty;
string content = File.ReadAllText(input_file1);
lst1 = content.Substring(0, content.IndexOf("ID_2"));
lst1 = lst1.Substring(0, lst1.IndexOf("End"));
start = content.IndexOf("ID_2");
lst2 = content.Substring(start);
lst2 = lst2.Substring(0, lst2.IndexOf("End")).Trim();
content = File.ReadAllText(input_file2);
lst1b = content.Substring(content.IndexOf("deg") + 5, content.IndexOf("ID_2"));
lst1b = lst1b.Substring(0, lst1b.IndexOf("End") + 3);
lst1 += lst1b + Environment.NewLine;
start = content.IndexOf("ID_2");
lst2b = content.Substring(start);
lst2b = lst2b.Substring(lst2b.IndexOf("deg") + 3);
lst2 += lst2b;
File.WriteAllText(outputfile, lst1 + lst2);