0

I want to load an XML file which is in D: drive. This is what I used

doc.Load(System.Web.HttpContext.Current.Server.MapPath("/D:/Employee.xml"));

But it gives me an error whenever I try to run my program:

Object reference not set to an instance of an object.

I read it somewhere that Server.MapPath can be used only for webpages or web apps. I made a form in asp.net using c#.

Why am I getting this error?

This is my code:

 private void btnRead_Click(object sender, EventArgs e)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load("D:\\Employee.xml");
        XmlNode root = doc.DocumentElement;
        StringBuilder sb = new StringBuilder();
        XmlNodeList nodeList = root.SelectNodes("Employee");
        foreach (XmlNode node in nodeList)
        {
            sb.Append("Name: ");
            //Select the text from a single node, “Title” in this case
            sb.Append(node.SelectSingleNode("Name").InnerText);
            sb.Append("EmpID: ");
            sb.Append(node.SelectSingleNode("EmpID").InnerText);
            sb.Append("Dept: ");
            sb.Append(node.SelectSingleNode("Dept").InnerText);
            sb.Append("");
        }
        System.Web.HttpContext.Current.Response.Write(sb.ToString());
    }

I have made a form in VS 2008. Saved the details in an XML file. And now want to display the output.

Esha
  • 391
  • 1
  • 9
  • 37

2 Answers2

3

Why not load directly:

doc.Load("D:\\Employee.xml");
cuongle
  • 74,024
  • 28
  • 151
  • 206
  • This worked perfectly. Thanks. But I was using : `System.Web.HttpContext.Current.Response.Write(sb.ToString());` method to display it. and Now that is showing an error! :/ – Esha Oct 04 '12 at 11:08
  • 1
    @syrion: Seem you use HttpContext.Current in different thread? – cuongle Oct 04 '12 at 11:09
  • Actually I made a form in vs 2008. So I'm pretty confused on how to load and display the output. I'll just edit my question and write the complete code. – Esha Oct 04 '12 at 11:13
  • @Syrion: could you test it again? – cuongle Oct 04 '12 at 17:29
2

In a desktop application there is not such HttpContext.Current, that's why you get the NullReferenceException. Instead, use

doc.Load("D:/Employee.xml");
Oscar
  • 13,594
  • 8
  • 47
  • 75