1

我有一个大约 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();
    }

它只复制最后一行。:(

4

3 回答 3

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);
于 2013-09-06T23:39:43.557 回答
2

您需要在 while 循环之前移动“file2”的创建。您还应该在 using: 中创建“文件”。那时你不需要为任何一个打电话 close 。

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);
            }
}
于 2013-09-06T23:49:04.757 回答
0

.WriteLine每次调用时,您的文件都会覆盖整个文件。因此,将整个代码放在您的using块中,或添加trueStreamWriter的参数以告诉它附加到文件而不是覆盖。

选项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);而不是整个usingStreamWriter

于 2013-09-06T23:40:25.257 回答