문제

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.

도움이 되었습니까?

해결책

Why not load directly:

doc.Load("D:\\Employee.xml");

다른 팁

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

doc.Load("D:/Employee.xml");
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top