日期:2014-05-17  浏览次数:20405 次

FileStream 未能找到路径的一部分。asp.net
代码如下,直接本地测试就出现错误。.net3.5的环境
C# code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.IO;

public partial class _Default : System.Web.UI.Page 
{
    private string file;
    protected void Page_Load(object sender, EventArgs e)
    {
        file = Path.Combine(Request.PhysicalPath, @"App_Data\SuperProductiList.xml");
    }
   
    protected void Button1_Click(object sender, EventArgs e)
    {
        
        FileStream fs = new FileStream(file, FileMode.Create);
        XmlTextWriter w = new XmlTextWriter(fs, null);

        w.WriteStartDocument();
        w.WriteStartElement("Super");
        w.WriteComment("This file generated by the XmlTextWriter class.");

        w.WriteStartElement("Product");
        w.WriteAttributeString("ID", "1");
        w.WriteAttributeString("Name", "Chair");
        w.WriteStartElement("price");
        w.WriteString("49.5");
        w.WriteEndElement();
        w.WriteEndElement();

        w.WriteEndElement();
        w.WriteEndDocument();
        w.Close();
    }
}



------解决方案--------------------
你看看
Request.PhysicalPath, @"App_Data\SuperProductiList.xml")
出来的路径是什么吧

是不存在的,。

直接
file = Server.MapPath("~/App_Data/SuperProductiList.xml");

SuperProductiList.xml放在根目录的app_Data下面
------解决方案--------------------
file = Path.Combine(Request.PhysicalPath, @"App_Data\SuperProductiList.xml");
Request.PhysicalPath

换成:
AppDomain.CurrentDomain.BaseDirectory
file = AppDomain.CurrentDomain.BaseDirectory + @"App_Data\SuperProductiList.xml";