簡體   English   中英

如何在文本文件的中間插入行?

[英]How to insert lines into the middle of a text file?

我有一個文本文件,遇到特定行后需要在其中添加一些行。

我嘗試制作一個流對象,然后從文件中讀取,直到獲得搜索文本,然后通過設置其光標位置寫入同一流,但是它不起作用。

有什么辦法嗎?

您可以在文件中間添加一些文本:

var sb = new StringBuilder();
using (var sr = new StreamReader("inputFileName"))
{
    string line;
    do
    {
        line = sr.ReadLine();
        sb.AppendLine(line);
    } while (!line.Contains("<Sim Properties>"));

    sb.Append(myText);
    sb.Append(sr.ReadToEnd());
}

using (var sr = new StreamWriter("outputFileName"))
{
    sr.Write(sb.ToString());
}

這將包含<Sim Properties>的行之后插入myText

下面的代碼示例演示使用WriteAllLines方法將文本寫入文件。 在此示例中,將創建一個文件(如果尚不存在),並向其中添加文本。

   using System;
    using System.IO;
    class Test
    {
        public static void Main()
        {
            string path = @"c:\temp\MyTest.txt";

            // This text is added only once to the file. 
            if (!File.Exists(path))
            {
                // Create a file to write to. 
                string[] createText = { "Hello", "And", "Welcome" };
                File.WriteAllLines(path, createText);
            }

            // This text is always added, making the file longer over time 
            // if it is not deleted. 
            string appendText = "This is extra text" + Environment.NewLine;
            File.AppendAllText(path, appendText);

            // Open the file to read from. 
            string[] readText = File.ReadAllLines(path);
            foreach (string s in readText)
            {
                Console.WriteLine(s);
            }
        }
    }

暫無
暫無

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

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