简体   繁体   English

使用Server.MapPath加载外部文件

[英]Use Server.MapPath to load external files

I want to load an XML file which is in D: drive. 我想加载D:驱动器中的XML文件。 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. 我在Server.MapPath仅可用于网页或Web应用程序的地方读到它。 I made a form in asp.net using c#. 我使用c#在asp.net中创建了一个表单。

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. 我已经在VS 2008中创建了一个表单。将详细信息保存在XML文件中。 And now want to display the output. 现在要显示输出。

为什么不直接加载:

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

In a desktop application there is not such HttpContext.Current, that's why you get the NullReferenceException. 在桌面应用程序中,没有这样的HttpContext.Current,这就是为什么要获取NullReferenceException的原因。 Instead, use 相反,使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM