c# - 读取文件,搜索术语并替换该术语的所有行

标签 c# winforms replace streamwriter

我做了一些研究,但找不到我的问题的答案。

我有这段代码可以搜索一个词并替换它。

重点是,在我的应用程序中,我想选择一些文件和文件夹路径,然后将该路径写入我的 .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/

相关文章:

c# - 帮助注册附加依赖属性

c# - 通知 WPF DataGrid 更改

c# - 为什么win32异常没有被c#异常处理机制捕获

c# - Sqlite数据库中的加密和解密?

sql - Oracle PL/SQL 中的字符串删除

c# - 使用 csvhelper 和 memorystream 时字节长度错误

c# - 变量名称长度对 C# 性能有影响吗?

c# - 使用int.TryParse C#时发生编译错误

xml - Powershell 错误 : Method invocation. ..不包含名为 'replace' 的方法

javascript - 如何在我的例子 "-"中查找字符串中的特定字符并将其替换为javascript js中的 "_"