本文介绍了我怎样才能在同一个文件中优雅地实现多个字符串替换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  File.WriteAllText(filePath,Regex)

现在我有一些代码来替换看起来像这样的文件中的字符串: .Replace(File.ReadAllText(filePath),
(+ column.Key +),
+ column.Value +
));
File.WriteAllText(filePath,Regex.Replace(File.ReadAllText(filePath),
(\\ [\+ column.Key +\\\] ),
[\+ column.Value +\]
));

然而,每个替换打开和关闭文件,似乎偶尔他们运行太快而且一个替换将不起作用,因为该文件在以前的字符串替换中还没有关闭。有没有我可以重复使用的代码解决这个问题,也许使用FileStream类(所以我可以打开和关闭一次)?或建议更好的方式来做到这一点?只是想知道是否有更简单的办法可以做,而不必创建字符串数组,我想要替换和写入代码读取,写入,并通过手动查找字节。谢谢。

解决方案

string contents = File.ReadAllText(filePath);
contents = Regex.Replace(contents,
(+ column.Key +),
+ column.Value +);
contents = Regex.Replace(contents,
(\\ [\+ column.Key +\\\)),
[ \+ column.Value +\]);
File.WriteAllText(filePath,contents);


Currently I have some code to replace strings in a file that looks like this:

File.WriteAllText(filePath, Regex.Replace(File.ReadAllText(filePath),
    "( " + column.Key + " )",
    " " + column.Value + " "
));
File.WriteAllText(filePath, Regex.Replace(File.ReadAllText(filePath),
    "(\\[\"" + column.Key + "\"\\])",
    "[\"" + column.Value + "\"]"
));

However, each replacement opens and closes the file, and it seems that occasionally they run "too fast" and one replacement will not work because the file did not close yet in a previous string replacement. Is there any code I can reuse that solves this issue, perhaps using the FileStream class (so I can open and close once)? Or suggestions on a better way to do this? Just wondering if there is something simpler I can do than having to create byte arrays of the strings I want to replace and writing code to read, write, and seek through bytes manually. Thanks.

解决方案
string contents = File.ReadAllText(filePath);
contents = Regex.Replace(contents,
    "( " + column.Key + " )",
    " " + column.Value + " ");
contents = Regex.Replace(contents,
    "(\\[\"" + column.Key + "\"\\])",
    "[\"" + column.Value + "\"]");
File.WriteAllText(filePath, contents);

这篇关于我怎样才能在同一个文件中优雅地实现多个字符串替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 11:02