Search code examples
c#xmlfilestreamstreamreaderstreamwriter

C# XML Father-Son update can not save


I'm trying to update an existing app. I was asked previously to simply clean out an xml file for escape characters, which were coming to us, prior to them being pulled through to the company system. Doing this allowed us the option of avoiding writing inside an app written 7 years ago and working fine (but ZERO documentation)

It actually worked fine with

foreach (string d in Directory.GetFiles(test, "*.xml", SearchOption.AllDirectories))
{
    String[] lines = File.ReadAllLines(d);
    for (int i = 0; i < lines.Length; i++)
    {
        if (lines[i].Contains("&amp;"))
        {
            i++;
        }
        //Replace incorrect characters
        else if (lines[i].Contains("&"))
        {
            log.Info(saveName);
            log.Error("Incorrect '&' Detected: Changing to '&amp;'");
            lines[i] = lines[i].Replace("&", "&amp;");
            log.Info(lines[i]);
        }

    }
    System.IO.File.WriteAllLines(d, lines);
}

And maybe too easily as I have been asked to try to integrate this with the main app, to prevent the operators having to do the pre-clean.

I know (well I believe) that I am missing the corresponding System.IO.File.WriteAllLines(d, lines); in the following code but I can not get it or anything else to work. The "replace" is working as the WriteLine is showing the corrected line(s) but I can not get the system to hold the changes.

MemoryStream ms = new MemoryStream();

ms.Position = 0;
List<string> rows = new List<string>();
using (var reader = new StreamReader(ms))
{
    string line;
    var sw = new StreamWriter(ms);
    while ((line = reader.ReadLine()) != null)
    {
        if (line.Contains("&"))
        {
            Console.WriteLine(line);
            line = line.Replace("&", "&amp;");
            sw.Write(line);
            Console.WriteLine(line);
        }
    }

Solution

  • Lesson is "when amending a large app, make sure to read it all".

    For some reason the original developer decided to dip back in to the zip file (where these files were received) and extract the whole thing again for the Stream.

    Changed that and it all works and is running much faster as a result.