是否有更有效的方法同时阅读和书写文本填充?

时间:2016-04-19 13:51:36

标签: c#

我又回到了另一个问题,这次是关于编辑文本文件的问题。我的家庭工作如下

Write a program that reads the contents of a text file and inserts the line numbers at the beginning of each line, then rewrites the file contents.

这是我到目前为止所做的,但我不确定这是否是最有效的方式。我此刻才开始学习如何处理文本文件。

        static void Main(string[] args)
    {
        string fileName = @"C:\Users\Nate\Documents\Visual Studio 2015\Projects\Chapter 15\Chapter 15 Question 3\Chapter 15 Question 3\TextFile1.txt";
        StreamReader reader = new StreamReader(fileName);

        int lineCounter = 0;
        List<string> list = new List<string>();

        using (reader)
        {
            string line = reader.ReadLine();
            while (line != null)
            {
                list.Add("line " + (lineCounter + 1) + ": " + line);
                line = reader.ReadLine();
                lineCounter++;
            }
        }

        StreamWriter writer = new StreamWriter(fileName);
        using (writer)
        {
            foreach (string line in list)
            {
                writer.WriteLine(line);
            }
        }
    }

您的帮助将不胜感激! 再次感谢。 :

3 个答案:

答案 0 :(得分:2)

这应该足够了(如果文件相对较小):

using System.IO;    
(...)

static void Main(string[] args)
{

    string fileName = @"C:\Users\Nate\Documents\Visual Studio 2015\Projects\Chapter 15\Chapter 15 Question 3\Chapter 15 Question 3\TextFile1.txt";
    string[] lines = File.ReadAllLines(fileName);

    for (int i = 0; i< lines.Length; i++)
    {
        lines[i] = string.Format("{0} {1}", i + 1, lines[i]);
    }
    File.WriteAllLines(fileName, lines);
}

答案 1 :(得分:1)

我建议使用Linq,使用File.ReadLines阅读内容。

// Read all lines and apply format
var formatteLines = File
  .ReadLines("filepath")  // read lines
  .Select((line, i) => string.Format("line {0} :{1} ",  line, i+1)); // format each line.

// write formatted lines to either to the new file or override previous file.
File.WriteAllLines("outputfilepath", formatteLines); 

答案 2 :(得分:0)

这里只有一个循环。我认为它会很有效率。

class Program
{
    public static void Main()
    {
        string path = Directory.GetCurrentDirectory() + @"\MyText.txt";

        StreamReader sr1 = File.OpenText(path);


        string s = "";
        int counter = 1;
        StringBuilder sb = new StringBuilder();

        while ((s = sr1.ReadLine()) != null)
        {
            var lineOutput = counter++ + " " + s;
            Console.WriteLine(lineOutput);

            sb.Append(lineOutput);
        }


        sr1.Close();
        Console.WriteLine();
        StreamWriter sw1 = File.AppendText(path);
        sw1.Write(sb);

        sw1.Close();

    }