Search code examples
xmlvb.netstreamreader

How to replace text in large XML file


When I tryto remove text in an xml file, ie. rsquo, I get a 'System.OutOfMemoryException' exception error.

Any advice? - Its written in vb

   <Person>
   <Name>&rsquo; John /&rsquo; </Name>
   <age> 24 </age>
   <DOB>
      <year> 1990 </year>
      <month> 03 </month>
      <date> 23 </date>
  </DOB>
</Person>

   Dim myStreamReaderL1 As StreamReader
   Dim myStream As StreamWriter
   Dim mystr As String

   myStreamReaderL1 = System.IO.File.OpenText(Server.MapPath( filepath_Label.Text))
   myStr = myStreamReaderL1.ReadToEnd() 
   myStreamReaderL1.Close()

   If mystr.Contains("&rsquo;") Then
     mystr = mystr.Replace("&rsquo;", "")
     count += count + 1
    End If

    myStream = System.IO.File.CreateText(Server.MapPath("Valedate/" & DateTime.Now.ToString("yyyy-MM-dd") & "/new" & TextBox_filename.Text))
    myStream.WriteLine(myStr)
    myStream.Close()

Solution

  • Here's your mistake:

    myStr = myStreamReaderL1.ReadToEnd() 
    

    You only need ReadToEnd() if you need repeated nonsequential access to widely-separated positions in your file. If you are doing that you should not be using a StreamReader. You should not use ReadToEnd() to perform sequential access, like replacing a string on every line. Do something like this:

    Using sr = System.IO.File.OpenText(Server.MapPath(filepath_Label.Text))
    Using sw = System.IO.File.CreateText(Server.MapPath("Valedate/" & DateTime.Now.ToString("yyyy-MM-dd") & "/new" & TextBox_filename.Text))
        Dim l As String
        l = sr.ReadLine
        Do While (Not l Is Nothing)
            If l.Contains("&rsquo;") Then
                l = l.Replace("&rsquo;", "")
            End If
    
            sw.WriteLine(l)
            l = sr.ReadLine
        End While
    End Using
    End Using