簡體   English   中英

是否有更有效的方式同時讀寫文本填充?

[英]Is there a more efficient way of reading and writing a text fill at the same time?

我再次提到另一個問題,這次是關於編輯文本文件。 我的家庭作業如下

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);
            }
        }
    }

您的幫助將不勝感激! 再次感謝。 :]

這應該足夠了(如果文件比較小):

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);
}

我建議使用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); 

這里只有一個循環。 我認為這將是有效的。

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();

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM