我有一个大约5,000行的文本文件,我想将其内容复制到另一个文件,但只有每行的前38个字符。
我目前有这段代码:
private void button1_Click(object sender, EventArgs e)
{
string line, line2;
System.IO.StreamReader file = new System.IO.StreamReader(@"c:\test.txt");
while ((line = file.ReadLine()) != null)
{
line2 = line.Substring(0, 38);
using (System.IO.StreamWriter files = new System.IO.StreamWriter(@"C:\test2.txt"))
{
files.WriteLine(line2);
}
}
file.Close();
}
它只复制最后一行。 :(
答案 0 :(得分:3)
因为你在循环中重写了你的新文件。你应该在循环中创建你的新字符串(使用stringBuilder会更有效),但是要把新文件写出循环:
string line;
var sb = new StringBuilder();
System.IO.StreamReader file = new System.IO.StreamReader(@"c:\test.txt");
while ((line = file.ReadLine()) != null)
sb.AppendLine(line.Substring(0, Math.Min(38, line.Length)));
file.Close();
using (System.IO.StreamWriter files = new System.IO.StreamWriter(@"C:\test2.txt"))
{
files.WriteLine(sb.ToString());
}
或缩短
var result = File.ReadAllLines(@"c:\test.txt")
.Select(m => m.Substring(0, Math.Min(38, m.Length)));
File.WriteAllLines(@"C:\test2.txt", result);
答案 1 :(得分:2)
您需要在while循环之前移动'file2'的创建。 您还应该在使用中创建“文件”:那么你不需要为任何一个打电话。
private void button1_Click(object sender, EventArgs e)
{
string line;
using (System.IO.StreamReader file = new System.IO.StreamReader(@"c:\test.txt"))
using (System.IO.StreamWriter file2 = new System.IO.StreamWriter(@"C:\test2.txt"))
while ((line = file.ReadLine()) != null)
{
string line2 = line.Substring(0, 38);
file2.WriteLine(line2);
}
}
答案 2 :(得分:0)
每次调用时,您的文件.WriteLine
都会覆盖整个文件。因此,将整个代码放在using
块中,或将true
添加到StreamWriter
的参数中,告诉它附加到文件而不是覆盖。
选项1:
private void button1_Click(object sender, EventArgs e)
{
string line, line2;
using (System.IO.StreamWriter files = new System.IO.StreamWriter(@"C:\test2.txt"))
{
System.IO.StreamReader file = new System.IO.StreamReader(@"c:\test.txt");
while ((line = file.ReadLine()) != null)
{
line2 = line.Substring(0, 38);
files.WriteLine(line2);
}
file.Close();
}
}
选项2:
private void button1_Click(object sender, EventArgs e)
{
string line, line2;
System.IO.StreamReader file = new System.IO.StreamReader(@"c:\test.txt");
while ((line = file.ReadLine()) != null)
{
line2 = line.Substring(0, 38);
using (System.IO.StreamWriter files = new System.IO.StreamWriter(@"C:\test2.txt",true))
{
files.WriteLine(line2);
}
}
file.Close();
}
最后,如果您选择使用StringBuilder,则可以使用System.IO.File.WriteAllText(@"C:\test2.txt", stringHere);
代替整个using
和StreamWriter
块