使用此代码将索引更改为1到50001,50002等。但它似乎没有保存在文本文件中。 有没有办法说file.Save?或者我在做些傻事。
这是我的代码
int count = 50000;
string line;
//string str = File.ReadAllText();
System.IO.StreamReader file =
new System.IO.StreamReader(@"C:\Documents\new\example\example.txt");
while ((line = file.ReadLine()) != null)
{
line = line.Replace(":1}}", ":" + count + "}}");
count++;
}
答案 0 :(得分:1)
您必须将更改的数据写回:
string path = @"C:\Documents\new\example\example.txt";
int count = 50000;
var target = File
.ReadLines(path)
.Select(line => line.Replace(":1}}", ":" + count++ + "}}"))
.ToList(); // materialization required if you want to write back to the same file
// You can here inspect, debug etc., what you're going to write back, e.g.
// Console.Write(string.Join(Environment.NewLine, target));
File.WriteAllLines(path, target);
答案 1 :(得分:0)
int count = 50000;
//string str = File.ReadAllText();
string fileName = @"C:\Documents\new\example\example.txt";
List<string> lines = new List<string>();
using (System.IO.StreamReader file =
new System.IO.StreamReader(fileName))
{
string line;
while ((line = file.ReadLine()) != null)
{
line = line.Replace(":1}}", ":" + count + "}}");
lines.Add(line);
count++;
}
}
using (StreamWriter sw = new StreamWriter(fileName,false))
{
foreach (string line in lines)
{
sw.WriteLine(line);
}
}