C# 试图从XMl文件中检索数据,但由于该文件正在使用,因此出现了错误
我正在尝试从Xml检索数据。我是编程新手,请原谅C# 试图从XMl文件中检索数据,但由于该文件正在使用,因此出现了错误,c#,xml,dataset,C#,Xml,Dataset,我正在尝试从Xml检索数据。我是编程新手,请原谅 protected void Page_Load(object sender, EventArgs e) { string MyXmlFile= @"E:\\Programming stuff\\Work\\website\\XMLFile.xml"; DataSet ds= new DataSet(); System.IO.FileStream MyReadXml= new System.IO.Fi
protected void Page_Load(object sender, EventArgs e)
{
string MyXmlFile= @"E:\\Programming stuff\\Work\\website\\XMLFile.xml";
DataSet ds= new DataSet();
System.IO.FileStream MyReadXml= new System.IO.FileStream(MyXmlFile, System.IO.FileMode.Open);
ds.ReadXml(MyReadXml);
DataGrid DataGrid1 = new DataGrid();
DataGrid1.DataSource = ds;
DataGrid1.DataBind();
}
我在浏览器上遇到的错误是:
“进程无法访问文件‘E:\Programming stuff\Work\website\XMLFile.xml’,因为它正被另一个进程使用。”
您能帮我确定访问该文件的另一个进程是哪个吗
编辑:更改代码后:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
string MyXmlFile= Server.MapPath("~/XMLFile.xml");
using(System.IO.FileStream MyReadXml= new System.IO.FileStream(MyXmlFile,System.IO.FileMode.Open));
{
DataSet ds= new DataSet();
ds.ReadXml(MyReadXml);
DataGrid DataGrid1 = new DataGrid();
DataGrid1.DataSource = ds;
DataGrid1.DataBind();
PlaceHolder1.Controls.Add(DataGrid1);
}
}
}
错误:“名称“MyReadXml”在当前上下文中不存在”完成工作后始终关闭流
将代码放置在using块中可确保控件一离开块,对象即被释放
始终
close
和dispose
流(尝试使用block)。重新启动appserver(werserver),看看会发生什么
if(!IsPostBack)
{
string MyXmlFile= @"E:\\Programming stuff\\Work\\website\\XMLFile.xml";
using(System.IO.FileStream MyReadXml=System.IO.File.OpenRead(MyXmlFile))
{
DataSet ds= new DataSet();
ds.ReadXml(MyReadXml);
//Add DataGrid control markup in .aspx.
DataGrid1.DataSource = ds.Tables[0];
DataGrid1.DataBind();
}
}
注意:如果XMLFile.xml
位于website
的根目录下,则使用Server.MapPath()
方法从虚拟路径获取绝对文件路径
string MyXmlFile= Server.MapPath("~/XMLFile.xml");
如果要以编程方式添加ASP.NET服务器控件,请将占位符
控件添加到.aspx文件中,并调用PlaceControl1.Controls.add(DataGrid1)
方法
string MyXmlFile= @"E:\\Programming stuff\\Work\\website\\XMLFile.xml";
using(System.IO.FileStream MyReadXml=System.IO.File.OpenRead(MyXmlFile))
{
DataSet ds= new DataSet();
ds.ReadXml(MyReadXml);
DataGrid DataGrid1=new DataGrid();
DataGrid1.DataSource = ds.Tables[0];
DataGrid1.DataBind();
PlaceHolder1.Controls.Add(DataGrid1);
}
编辑:
我仍然得到错误,因为“MyReadXml不存在”我做错了什么吗
您已终止使用块。请去掉分号
using(System.IO.FileStream MyReadXml=new
System.IO.FileStream(MyXmlFile,System.IO.FileMode.Open))
{
...
}
我尝试了一下,但它给了我另一个错误:“名称'MyReadXml'在当前上下文中不存在”@u r使用它超出范围,意味着超出范围block@whatever我对编程术语的了解有限。你能告诉我你说的街区是什么意思吗?我按照您的建议对代码进行了更改。在您的问题中,再次粘贴新的所有代码,我想查看整个代码xml文件确实位于目录中,因此遵循了您使用Server.MapPath的建议。还在.aspx文件中添加了占位符控件。我仍然收到错误,因为“MyReadXml不存在”我做错了什么吗?您已使用块终止了
。请去掉分号。太棒了!成功了。我收到了某种警告,可能是空洞的声明,但我忽略了它。非常感谢。它现在正在工作。
using(System.IO.FileStream MyReadXml=new
System.IO.FileStream(MyXmlFile,System.IO.FileMode.Open))
{
...
}