c# - 更改 txt 文件中的行

标签 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?

最佳答案

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

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

关于c# - 更改 txt 文件中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33671606/

相关文章:

c# - 是否可以在 Windows 10 上调整 BLE 连接间隔?

c# - 加载程序集时出现异常 : System. IO.FileNotFoundException : Could not load assembly 'System. ValueTuple,版本 = 4.0.2.0,

c# - 使用反射调用传递 lambda 表达式的泛型方法

c# - 当我有一个实体时,动态地在 DbContext 中查找指定的通用 DbSet

c# - 数据库函数 "cannot be translated into a LINQ to Entities store expression"

c# - 如果线程正在等待异步操作完成,.NET Task 线程的资源是否会暂时返回池中?

c# - 单击按钮时 gridview 内的文本框值为空

c# - 单声道互操作 : Loading 32bit shared library does not work on my 64bit system

c# - 使用 C# 将所有引号设置为双引号

c# - Unity 如何在检查器中删除数组中的元素标签(Element 0 - Element ...)