我做了一些研究,但找不到我的问题的答案。
我有这段代码可以搜索一个词并替换它。
重点是,在我的应用程序中,我想选择一些文件和文件夹路径,然后将该路径写入我的 .properties 文件,以便“值”始终在变化。
在我的 .properties
文件中,我有 db.host=localhost
,我想将其更改为用户选择的主机名,例如 db。主机=我的主机
。这是我的代码:
string originalFile = @"C:\wamp\bin\php\php5.4.3\build.properties";
string outputFile = @"C:\wamp\bin\php\php5.4.3\build1.properties";
string searchTerm = "db.host=";
string replaceTerm="db.host=" + tbhost.Text ;
string tempLineValue;
using (FileStream inputStream = File.OpenRead(originalFile))
{
using (StreamReader inputReader = new StreamReader(inputStream))
{
using (StreamWriter outputWriter = File.AppendText(outputFile))
{
while (null != (tempLineValue = inputReader.ReadLine()))
{
outputWriter.WriteLine(tempLineValue.Replace(searchTerm, replaceTerm));
}
}
}
}
所以现在,如果我搜索 db.host=
并将其更改为 "db.host="+ tbhost.Text
,我文件中的结果是 db.host=myhostoldhost
假设我的 tbhost.Text=myhost
和最旧的值是“oldhost”。所以我需要的是找到 db.host=
删除所有行然后写入该行。
最佳答案
在写入文件之前使用以下代码
Regex r = new Regex(@"\s");
String[] tokens = r.Split(tempLineValue);
string settings = string.Empty;
for (int i = 0; i < tokens.Length; i++)
{
if (tokens[i].Contains(searchTerm))
{
settings = tokens[i];
break;
}
}
if (settings != string.Empty)
outputWriter.WriteLine((tempLineValue.Replace(settings, replaceTerm));
else
outputWriter.WriteLine(tempLineValue);
假设:您的主人只有一个词。
关于c# - 读取文件,搜索术语并替换该术语的所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18900985/