Search code examples
asp.netxmlwriter

XML does not get saved in asp.net


I have a problem saving my xml-file. i use this XMLwriter :

 using (XmlWriter writer = XmlWriter.Create("CarsXML.xml"))
            {
                writer.WriteStartDocument();
                writer.WriteStartElement("CarsXml");
                foreach (Car item in cars)
                {
                    writer.WriteStartElement("Car");
                    writer.WriteElementString("Brand", item.Brand);
                    writer.WriteElementString("Type", item.Type);
                    writer.WriteElementString("Price", item.Price);
                    writer.WriteElementString("Effect", item.Effect);
                    writer.WriteElementString("Year", item.year);
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Close();

        }

Seems ok right? No compile errors.. I´ve also tried this just for testing :

XDocument doc = new XDocument(
    new XElement("Root",
        new XElement("Child", "content")
    )
);
            doc.Save("Root.xml");

Still no luck.. `ve trid this in a console app, and it works so the code must be fine.. I´ve also tried with a piece of code i found somewhere - using XmlDocument instead - but its the same deal.

What am i doing wrong?


Solution

  • When you are in a web application, the current directory is not the root directory of the web application. It's the directory where the IIS executable is, so that's somewhere in the Windows system directories.

    Naturally you don't have write access to that directory from the web application, so you get some exception when you try to create a file there.

    Specify the full path of the file that you want to create. You can use the MapPath method to get the physical path to a file from a virtual path. Example:

    string fileName = Server.MapPath("/xmldata/CarsXML.xml");
    
    using (XmlWriter writer = XmlWriter.Create(fileName))
      ...