none
StreamWriter problem RRS feed

  • Question

  • I am using this operation to copy the contents of a web XML page to a local disk .XML file. The problem I have run into is that the information near the end of the XML file gets lost.   </span>
    
    
    <br/>
    
    
    HttpWebRequest request = WebRequest.Create("http://www.wiu.edu/users/cv103/60014.xml") as HttpWebRequest;
    
    
    
     // Get response  
    
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
    
                {
    
                    // Get the response stream  
    
                    StreamReader reader = new StreamReader(response.GetResponseStream());
    
    
    
                    // Read the whole contents and return as a string  
    
                    xmlWeatherData = reader.ReadToEnd();
    
    
    
                    SaveXMLFile(xmlWeatherData);
    
    
    
                    ParseXML parser = new ParseXML();
    
                    parser.ParseXMLFile(xmlWeatherData);
    
    
    
                }
    
            }
    
    
    
                public void SaveXMLFile(string xmlWeatherData)
    
                {
    
    
    
                    FileStream fs = File.Create("weather.xml");
    
                    StreamWriter writer = new StreamWriter(fs);
    
                    writer.Write(xmlWeatherData);
    
                    fs.Close();
    
    
    Wednesday, April 14, 2010 1:31 AM

Answers

  • The StreamWriter should be closed prior to the FileStream.  (By not following this order, the StreamWriter might contain data but is not told to flush it.)

    Instead of calling Close directly, I would recommend "using" with the FileStream and StreamWriter to ensure they are closed properly.

    using (FileStream fs = ...)

    {

        using (StreamWriter writer = ...)

        {

        }

    }

    Wednesday, April 14, 2010 2:03 AM