gpt4 book ai didi

c# - 以只读访问模式加载 XML 文档

转载 作者:太空宇宙 更新时间:2023-11-03 13:07:52 24 4
gpt4 key购买 nike

如何以只读模式加载 XML 文档?

我有一个在另一个进程中打开的 XML 文件,我想将它以只读方式加载到我的 C# 应用程序中。

XmlDocument.Load("file.xml") 显然会抛出这个错误:

Process cannot access a file because it is being used by another process

所以我也尝试了流阅读器:

FileStream fs = new FileStream("file.xml", FileMode.Open, FileAccess.Read);
xmldoc.Load(fs);

但它也会抛出同样的错误。那么如何以只读模式访问我的 XML 文档呢?

更新

我也尝试了 XPathDocumentFileStream("file.xml", FileMode.Open, FileAccess.Read,FileShare.Read)。但他们都没有解决问题。

最佳答案

此类以只读模式显示读取的 xml 文件。

 public List<string[]> GetRunningOrderOnTable(string tableNo, int shopid)
{
try
{
XmlDocument xmlDoc = new XmlDocument();
string xmlFilePath = @"C:\inetpub\wwwroot\ShopAPI\XmlData\RunningTables.xml";
//string xmlFilePath = HttpContext.Current.Server.MapPath("~/XmlData/RunningTables.xml");
// Option 1
// FileStream xmlFile = new FileStream(xmlFilePath, FileMode.Open,
//FileAccess.Read, FileShare.Read);
// xmlDoc.Load(xmlFile);
// Option 2
using (Stream s = File.OpenRead(xmlFilePath))
{
xmlDoc.Load(s);
}
//xmlDoc.Load(xmlFilePath);
List<string[]> st = new List<string[]>();
XmlNodeList userNodes = xmlDoc.SelectNodes("//Tables/Table");
if (userNodes != null)
{
foreach (XmlNode userNode in userNodes)
{
string tblNo = userNode.Attributes["No"].Value;
string sid = userNode.Attributes["ShopID"].Value;
if (tblNo == tableNo && sid == shopid.ToString())
{
string[] str = new string[5];
str[0] = userNode.Attributes["No"].Value;
str[1] = userNode.InnerText; // OrderNumber
str[2] = userNode.Attributes["OrderID"].Value;
str[3] = userNode.Attributes["OrderedOn"].Value;
str[4] = userNode.Attributes["TotalAmount"].Value;
st.Add(str);
}
}
}
else return new List<string[]>();
return st;
}
catch (Exception ex)
{

CustomLogging.Log("RunningTables.xml GetRunningOrderOnTable Error " + ex.StackTrace, LoggingType.XMLRead);
return new List<string[]>();
}
}

关于c# - 以只读访问模式加载 XML 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30161094/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com