更改txt文件中的行

时间:2015-11-12 12:39:48

标签: c#

有点新的C#

是否有使用c#?

更改txt文件中的文本

我想打开一个包含以下内容的文本文件:

8881
8882
8883
8884
8885

将它们放在一个数组中,将行改为:

'8881',
'8882',
'8883',
'8884',
'8885',

然后用改变的行写出一个新的txt文件。

string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Public\TestFolder\WriteLines2.txt");

//Foreach that lists all lines
System.Console.WriteLine("WriteLines2.txt contains following lines = ");
foreach (string line in lines)
{         
    Console.WriteLine(line);
}

我如何能够改变每一行并将其写入新的txt?

5 个答案:

答案 0 :(得分:7)

您可以使用以下简单的LINQ查询和File.WriteAllLines

var newLines = from line in System.IO.File.ReadAllLines(filePath)
               select String.Format("'{0}',", line);
System.IO.File.WriteAllLines(filePath, newLines);

答案 1 :(得分:1)

您可以使用新行覆盖同一文件。

String path = @"C:\Users\Public\TestFolder\WriteLines2.txt";
String[] lines = System.IO.File.ReadAllLines(path);
//I'm using System.Linq to change the lines. I'm adding a "'" before and after the original token.
String[] changedLines = lines.Select(x => string.Format("'{0}',", x)).ToArray();

// I'm saving the changes to the file.
System.IO.File.WriteAllLines(path, changedLines);

您也可以在没有System.Linq

的情况下执行此操作
string[] path = @"C:\Users\Public\TestFolder\WriteLines2.txt";
string[] lines = System.IO.File.ReadAllLines(path);

// change every line
for (int index = 0; index < lines.Length; ++index)
{         
    lines[index] = string.Format("'{0}',", lines[index]);
}

System.IO.File.WriteAllLines(path, lines);

答案 2 :(得分:0)

var linesModified = lines.Select (l => string.Format(@"'{0}',",l));
File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines2_Out.txt", linesModified);

编辑:高效版本使用流式传输而不是将整个文件加载(可能是一个大文件)到内存中:

void Main()
{
  string inFileName = @"C:\Users\Public\TestFolder\WriteLines2.txt";
  string outFileName = @"C:\Users\Public\TestFolder\WriteLines2_Out.txt";

  using(var r = File.OpenText(inFileName))
  using(var w = File.CreateText(outFileName))
  {
    string line;
    while ( (line = r.ReadLine()) != null)
    {
        w.WriteLine(string.Format(@"'{0}',",line));
    }
  }
}

答案 3 :(得分:0)

你可以尝试使用linq

//read the fine and alter it by Select Function 
        var lines = File.ReadAllLines("file.txt").Select(item =>  string.Format("'{0}',",item)).ToArray();
    //write the lines to disk
    File.WriteAllLines("file02.txt",lines);

答案 4 :(得分:0)

试试这个 -

var file = File.ReadLines("path");
var sb = new StringBuilder();
foreach (var t in file)
{
   if(!string.IsNullOrWhiteSpace(t))
        sb.AppendLine("'" + t + "',");
}
File.WriteAllLines("path", new string[] { sb.ToString() });