Click here to Skip to main content
15,923,852 members
Please Sign up or sign in to vote.
4.00/5 (3 votes)
See more:
Hi I am getting this error:
Read_Insert_Data_Into_XML_File/App_Data/Sample.xml' is a physical path, but a virtual path was expected.

This is my code:
protected void btnSubmit_Click(object sender, EventArgs e)
   {
       XmlDocument xmlDoc = new XmlDocument();
       string xmlPath = Path.Combine(Server.MapPath("~/App_Data"), "Sample.xml");
       if (!File.Exists(xmlPath))
       {
           throw new Exception("Cannot find xml file");
       }
       else
       {
           xmlDoc.Load(Server.MapPath(xmlPath));
           XmlElement parentElement = xmlDoc.CreateElement("Comments");
           XmlElement name = xmlDoc.CreateElement("Name");
           name.InnerText = txtName.Text;
           parentElement.AppendChild(name);
           parentElement.AppendChild(Location);
           xmlDoc.DocumentElement.AppendChild(parentElement);
           xmlDoc.Save(Server.MapPath(xmlPath));
           BindDataList();
    }

I am getting an error at this line of code:
xmlDoc.Load(Server.MapPath(xmlPath));
Posted

You already converted the virtual path to a physical path, so the second time you try the conversion fails as it already is a physical path:

protected void btnSubmit_Click(object sender, EventArgs e)
    {
        XmlDocument xmlDoc = new XmlDocument();
        string xmlPath = Path.Combine(Server.MapPath("~/App_Data"), "Sample.xml"); // The conversion is done here, by Server.MapPath
        if (!File.Exists(xmlPath))
        {
            throw new Exception("Cannot find xml file");
        }
        else
        {
            //xmlDoc.Load(Server.MapPath(xmlPath));   // Error happens here too
            xmlDoc.Load(xmlPath);                     // Same as below 
            XmlElement parentElement = xmlDoc.CreateElement("Comments");
            XmlElement name = xmlDoc.CreateElement("Name");
            name.InnerText = txtName.Text;
            parentElement.AppendChild(name);
            parentElement.AppendChild(Location);
            xmlDoc.DocumentElement.AppendChild(parentElement);
            //xmlDoc.Save(Server.MapPath(xmlPath)); // Error happens here as the path was already a physical path
            xmlDoc.Save(xmlPath);                   // Just leave out the Server.MapPath call
            BindDataList();
     }


Regards,

— Manfred
 
Share this answer
 
v3
Comments
Manfred Rudolf Bihy 6-May-13 7:04am    
Forgot to patch the xmlDoc.Load along with xmlDoc.Save. :doh:
Joezer BH 6-May-13 9:24am    
5ed!
Manfred Rudolf Bihy 6-May-13 9:51am    
Thanks Edo! :)
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900