更新文件中的字符串 [英] updating string in file
本文介绍了更新文件中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在没有文本编辑器的情况下从文件或文本文件的最后一行删除字符串?
How to delete a string from the last line from a file or text file without a text-editor ?
推荐答案
将整个文件加载到内存中,然后重写文件,但最后一行除外.
Load the entire file into memory, and then rewrite the file with the exception of the last line.
^ ]一篇老文章,可以帮助您入门.
Here''s[^] an old article that will get you started.
可能会有所帮助,
might helps,
string stringToDelete = "test";
string fileName = @"c:\temp\test.txt";
var result = File.ReadLines(fileName).Select(line => line.Contains(stringToDelete) ? line.Replace(stringToDelete, string.Empty) : line);
然后将结果重写回文件.重写代码如下,
and then do the rewrite the result back to the file. The code for rewriting is below,
string rollBackContents = default(string);
foreach (var item in result)
{
rollBackContents = string.Concat(rollBackContents, item,Environment.NewLine);
}
File.WriteAllText(fileName, rollBackContents);
希望对您有所帮助:)
Hope it helps :)
这篇关于更新文件中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文