如何在文本文档中添加新行

时间:2013-12-26 12:33:43

标签: c# text

我想知道,如何在文本文档中添加新行。例如,我有一个包含数字或其他内容的文本文档,其中包含以下两行文本:

“444444

323233"

我想添加一个新行,其中想添加新的数字组合,那么我该怎么做呢?我首先保存数组中的所有行,打印它们并要求用户选择要编辑的行以及所选行是否不存在(在这种情况下,如果用户在变量n中键入数字“3”),我想要创建新行的程序。

string path = C:\...\text1.text
string[] lines = File.ReadAllLines(path);
int i = 1;

foreach (var line in lines)
{
     Console.WriteLine("{0}. {1}", i, line);
     i++;
}

Console.Write("Choose which line to edit: ");
int n = int.Parse(Console.ReadLine());
n--;

Console.Write("{0}. ", n + 1);
lines[n] = lines[n].Replace(lines[n], Console.ReadLine());

File.WriteAllLines(path, lines);

谢谢!

3 个答案:

答案 0 :(得分:0)

Environment.NewLine属性获取为此环境定义的换行符字符串。

// Sample for the Environment.NewLine property 
 using System;

  class Sample 
   {
      public static void Main() 
      {
         Console.WriteLine();
         Console.WriteLine("NewLine: {0}  first line{0}  second line{0}  third line",
                      Environment.NewLine);
      }
   }
   /*
        This example produces the following results:

         NewLine:
         first line
         second line
         third line
    */

答案 1 :(得分:0)

使用提及代码替换以下代码行:

 string path = C:\...\text1.text
 List<string> lines = File.ReadAllLines(path);
 int i = 1;

 foreach (var line in lines)
{
   Console.WriteLine("{0}. {1}", i, line);
   i++;
 }

  Console.Write("Choose which line to edit: ");
  int n = int.Parse(Console.ReadLine());
  n--;

 Console.Write("{0}. ", n + 1);

lines.Insert(n, Console.ReadLine());

File.WriteAllLines(path, lines.ToArray()); 

答案 2 :(得分:-1)

看看这里:

AppendAllText

对于所有文件方法:

File Methods

AppendAllText有一个签名:

public static void AppendAllText(
    string path,
    string contents
)

使用:

File.AppendAllText("path/to/file/that/exists/myfile.txt", "Your new line here");