繁体   English   中英

如何附加到文件中的文本

[英]How to append to a text in a file

我有一个包含以下内容的文件:

#Mon Jun 16 14:47:57 EDT 2014
DownloadDir=download
UserID=1111113
InputURL=https\://sdfsfd.com
DBID=1212
VerificationURL=https\://check.a.com
DownloadListFile=some.lst
UploadListFile=some1.lst
OutputURL=https\://sd.com
Password=bvfSDS3232sdCFFR

我想打开文件并修改内容, |TEST ONLY|TEST ONLY添加到UserID的末尾。 编辑后的文件将是这样的:

#Mon Jun 16 14:47:57 EDT 2014
DownloadDir=download
UserID=1111113|TEST ONLY
InputURL=https\://sdfsfd.com
DBID=1212
VerificationURL=https\://check.a.com
DownloadListFile=some.lst
UploadListFile=some1.lst
OutputURL=https\://sd.com
Password=bvfSDS3232sdCFFR

我该如何实现?

到目前为止,我已经能够从文件中读取所有行。 这就是我所拥有的:

if (File.Exists(strRootPropertyFile))
{
    string[] lines = null;
    try
    {
        lines = File.ReadAllLines(strRootPropertyFile);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

    if (lines != null)
    {
        //find the line with the UserID
        //add `|TEST ONLY` at the end of the UserID
        //Overwrite the file...
    }
}

您可以在各行之间循环,并检查该行是否以"UserID="字符串开头,并添加所需的字符串。 之后,创建一个新文件,并使用File.WriteAllText()方法和string.Join使用Environment.NewLine File.WriteAllText() string.Join )作为分隔符覆盖当前文件。

if (File.Exists(strRootPropertyFile))
{
    string[] lines = null;
    try
    {
        lines = File.ReadAllLines(strRootPropertyFile);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

    if (lines != null)
    {
        for(int i = 0; i < lines.Length; i++)
            if (lines[i].StartWith("UserID="))
                lines[i] += "|TEST ONLY";               

        File.WriteAllText(strRootPropertyFile, string.Join(Environment.NewLine, lines));
    }
}

我认为最好的方法是:

  • 逐行读取文件
  • 将行(可能已修改)写入另一个文件。
  • 取出原来的一个。
  • 重命名新文件!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM