0

I have an xml file with structure like this:

<ArrayOfUser
<User>
    <FirstName>John</FirstName>
</User>
</ArrayOfUser

I am attempting to grab information from a form and with it append to the xml file.

In my home controller I have this code:

[HttpPost]
        public string writeMe()
        {
            string xmlFilePath = @"~App_Data/users.xml";
            XmlDocument doc = new XmlDocument();
            doc.Load(xmlFilePath);
            XmlElement foo = doc.CreateElement("User");
            XmlElement bar = doc.CreateElement("FirstName");
            bar.InnerText = "Test";
            foo.AppendChild(bar);
            doc.DocumentElement.AppendChild(foo);
            doc.Save(xmlFilePath);
            return null;
        }

My JS code is this (not currently passing anything for testing purposes):

var FirstName = $("input[name='FirstName']").val();

     $.post("/Home/writeMe",
                {},
                function (response) {
                    alert("test");
                }
            );    

I get the following error: "Could not find a part of the path 'C:\Program Files (x86)\IIS Express\~App_Data\users.xml'.'"

I have tried other paths such as ...App_Data\users.xml, etc to no avail. Besides this error I am not confident I am approaching this correctly as I am VERY new to using MVC and use to winforms. Any tips or help would be greatly appreciated.

4
  • string xmlFilePath = @"~App_Data/users.xml"; should be string xmlFilePath = @"~/App_Data/users.xml"; It lacks a '/'. Commented Jun 1, 2017 at 16:56
  • Jose when I change it I now get System.IO.DirectoryNotFoundException: 'Could not find a part of the path 'C:\Program Files (x86)\IIS Express\~\App_Data\users.xml'.' Commented Jun 1, 2017 at 16:58
  • 1
    Oh, ok: doc.Load(Server.MapPath(xmlFilePath)). The same in the save Commented Jun 1, 2017 at 17:00
  • 1
    Thank you Jose! that fixed it Commented Jun 1, 2017 at 17:03

1 Answer 1

1

Follow these two steps to fix your issue:

  1. Put users.xml into App_Data-folder in your Visual Studio web project.
  2. Get path App_Data-folder with this Server.MapPath("~/App_Data");
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.