我的代码是
Dictionary<string,string> members = new Dictionary<string,string>();
//.. initialization of this dictionary
using (StreamWriter file = new StreamWriter(pathToFile))
foreach (var entry in members)
file.WriteLine("[{0} {1}]", entry.Key, entry.Value);
我需要在文件“testString”中出现的第一个指定字符串之后编写这些内容。如何轻松完成?
答案 0 :(得分:1)
您是否需要在中间插入数据(即 引用:“在这个文件中可能出现的第一个指定字符串之后写这个东西”)?
Dictionary<string, string> members = new Dictionary<string, string>();
String lineToFind = "testString";
// Let's read the file up in order to avoid read/write conflicts
var data = File
.ReadLines(pathToFile)
.ToList();
var before = data
.TakeWhile(line => line != lineToFind)
.Concat(new String[] {lineToFind}); // add lineToFind
var after = data
.SkipWhile(line => line != lineToFind)
.Skip(1); // skip lineToFind
var stuff = members
.Select(entry => String.Format("[{0} {1}]", entry.Key, entry.Value));
File.WriteAllLines(pathToFile, before
.Concat(stuff)
.Concat(after));
答案 1 :(得分:0)
您可以从文件中读取所有内容并以字符串形式存储。然后找到指定子字符串的索引并插入新值。然后使用以下命令回写文本文件:
using (StreamWriter file = new StreamWriter(pathToFile, false)){}
答案 2 :(得分:0)
创建一个临时文件并逐行写入所有数据,同时遍历所有行搜索指定的字符串并将数据插入到找到它的位置。同时尽量减少内存消耗。
Dictionary<string, string> members = new Dictionary<string, string>();
//.. initialization of this dictionary
string pathToFile = "";
string tempfile = Path.GetTempFileName(); //create a temp file
using (var writer = new StreamWriter(tempfile))
using (var reader = new StreamReader(pathToFile))
{
//if file is not ended
while (!reader.EndOfStream)
{
//get next line
string line = reader.ReadLine();
//write it to the "temp file"
writer.WriteLine(line);
//search in the line, if found, insert your data
if (line.Contains("search what you need"))
{
foreach (var entry in members)
writer.WriteLine("[{0} {1}]", entry.Key, entry.Value);
}
}
}
//overwrite the actual file with temp file
File.Copy(tempfile, pathToFile, true);