1
<namespace>
<root>
<node1>
<element 1>
<element 1>
</node1>
<node2>
<element 1>
<element 1>
</node2>
</root>

string stringContains = string.Empty;
                foreach(string line in File.ReadLines(Path))
                {
                    if(line.Contains("<Root>"))
                    {
                        stringContains = line.Replace("<Root>", "<Root>" + newelement.OuterXml);
                    }
                }
File.AppendAllText(Path, stringContains);

I must replace root with other nodes, so that i am appending text. However the above code appends existing text with stringContains

ND's
  • 2,155
  • 6
  • 38
  • 59
  • 3
    Looks like an XML document. Why aren't you using the proper XML parser built into .Net and manipulating the document that way? – PhonicUK Feb 07 '13 at 12:31
  • You should consider performing this task using Xsl transformation instead of text parsing. – Filburt Feb 07 '13 at 12:32
  • 1
    my file is in GB so i dont want to load file in xmlDocumnet for performance issue thats why..... what i do i m checking root node from line by lines and then replace root node with new nodes and append to existing file.....thts my scenaro.. – ND's Feb 07 '13 at 12:35
  • Use json. It is quite fast, – fhnaseer Feb 07 '13 at 12:40
  • how in windows form application... – ND's Feb 07 '13 at 12:41

2 Answers2

0

Try this.

string stringContains = string.Empty;
var lines = File.ReadLines(Path);
foreach (var line in lines)
{
    if(line.Contains("<Root>"))
    {
        stringContains = line.Replace("<Root>", "<Root>" + newelement.OuterXml);
    }
}
File.WriteAllLines(Path, lines);

but if your file size is huge then this is bad practise.

fhnaseer
  • 7,159
  • 16
  • 60
  • 112
0

Note: You cannot change just one line in a file, you need to read all content, change desired part and write all content again.

According to your info about file size (GBs long) your only way to achive desired behaviour is to create new file and write content of you initial file changing only lines you need.

Procesing should be done line-by-line (as you showed in your sample) to achive minimum use of memory

However, this approach requieres 2X space on your HDD till operation is complete (assuming you will delete initial file after all is done)

Regarding details: this question provides complete sample of how to achive described approach

Community
  • 1
  • 1
Nogard
  • 1,779
  • 2
  • 18
  • 21