【发布时间】:2014-12-18 10:09:43
【问题描述】:
我尝试获取 2 个 txt 文件并将 file1 中的每一行与 file2 中的每一行连接起来的行
示例: 文件1:
a
b
文件2:
c
d
结果:
a c
a d
b c
b d
这是代码:
{
//int counter = 0;
string[] lines1 = File.ReadLines("e:\\1.txt").ToArray();
string[] lines2 = File.ReadLines("e:\\2.txt").ToArray();
int len1 = lines1.Length;
int len2 = lines2.Length;
string[] names = new string[len1 * len2];
int i = 0;
int finish = 0;
//Console.WriteLine("Check this");
for (i = 0; i < lines2.Length; i++)
{
for (int j = 0; j < lines1.Length; j++)
{
names[finish] = lines2[i] + ' ' + lines1[j];
finish++;
}
}
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"E:\text.txt"))
{
foreach (string line in names)
{
// If the line doesn't contain the word 'Second', write the line to the file.
file.WriteLine(line);
}
}
}
我得到了这个例外:
“发生了“System.OutOfMemoryException”类型的未处理异常 在 ConsoleApplication2.exe 中”这一行:
字符串[] 名称 = 新字符串[len1 * len2];
有没有其他方法可以组合这两个文件而不会出现 OutOfMemoryException?
【问题讨论】:
-
文件有多大?
-
把你的for循环放在“Using”里面,而不是“names[finish] =”,直接把它写到文件中:“file.WriteLine(lines2[i] + ' ' + lines1[j]);", 这样您就不必创建字符串[] 名称
-
合并后文件均为400,000,000行
标签: c# arrays string out-of-memory