Si8
Si8

Reputation: 9235

How to append to a text in a file

I have a file which has the following contents:

#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

I would like to open the file and modify the contents, to add |TEST ONLY to the end of the UserID. The edited file will be this:

#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

How can I achieve it?

I so far have the ability to read all the lines from a file. This is what I have:

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...
    }
}

Upvotes: 0

Views: 68

Answers (2)

AHH
AHH

Reputation: 1083

The best to do, I think, is to:

  • Read the file line by line
  • Write the lines, possibly modified, into another file.
  • Remove the original one.
  • Rename the new file!

Upvotes: 1

Felipe Oriani
Felipe Oriani

Reputation: 38638

You could loop between lines and check if the line start with the "UserID=" string and add the string you need. After it, create a new file and overwrite the current file using the File.WriteAllText() method, and string.Join using the Environment.NewLine (break line) as separator.

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));
    }
}

Upvotes: 4

Related Questions