我有这个文件有很多字符串和许多替换,我想用替换字符串替换字符串,然后保存文本文件,这是我试过的,虽然做得不好:
StreamReader sr = new StreamReader(fullPath + "\\DICT_J.txt", Encoding.Unicode);
string cdID;
string str;
while (sr.Peek() >= 0)
{
string[] temp = sr.ReadLine().Split('^');
if (temp.Length == 3)
{
cdID = temp[1];
str = temp[2];
File.WriteAllText(path, Regex.Replace(File.ReadAllText(path), str, cdID), Encoding.Unicode);
}
}
sr.Close();
sr.Dispose();
here(抱歉,我无法在此处发布,因为SOF不允许Line返回)是包含替换的文件示例,这里是模板: 行ID ^替换^要替换的字符串
答案 0 :(得分:2)
不确定这是否有帮助,但这些是我的猜测。 这些方法有其他的编码重载,我在这里没有使用,但在你的情况下可能会有用。
public void Replace(string originalFile, string replacementsFile)
{
var originalContent = System.IO.File.ReadAllLines(originalFile);
var replacements = System.IO.File.ReadAllLines(replacementsFile);
foreach(var replacement in replacements)
{
var _split = replacement.Split(new char[] { '^' });
var lineNumber = Int32.Parse(_split[0]);
// checks if the original content file has that line number and replaces
if (originalContent.Length < lineNumber)
originalContent[lineNumber] = originalContent[lineNumber].Replace(_split[1], _split[2]);
}
System.IO.File.WriteAllLines(originalFile, originalContent);
}
public void Replace(string originalFile, string replacementsFile)
{
var originalContent = System.IO.File.ReadAllText(originalFile);
var replacements = System.IO.File.ReadAllLines(replacementsFile);
foreach(var replacement in replacements)
{
var _split = replacement.Split(new char[] { '^' });
originalContent = originalContent.Replace(_split[1], _split[2]);
}
System.IO.File.WriteAllText(originalFile, originalContent);
}