该进程无法访问该文件,因为它正由 EF Core 序列化 XML ---的另一个进程使用



我正在尝试编写一种方法来从罗斯文数据库中获取类别及其各自的产品,然后使用 xml 序列化写入文件。

我尝试了以下代码,但标题中详细说明了错误。(已创建文件,但未向其写入 XML(。

有人能建议我的代码有什么问题吗? 任何协助将不胜感激。谢谢。

static async void SerializeCategoriesWithXML() {
FileStream xmlFileStream = null;
XmlWriter xml = null;
// Create file to write to :
string path = Combine(CurrentDirectory, "CategoriesAndTheirProducts.xml");
// Create a file stream :
xmlFileStream = File.Create(path);
// Wrap the file stream in an Xml writer helper and automatically indent the nested elements :
xml = XmlWriter.Create(xmlFileStream, new XmlWriterSettings { Indent = true });
using (var db = new NorthwindContext())
{
// A query to get all categories and their related products :   
IQueryable<Categories> cats = db.Categories
.Include(c => c.Products
.ToList());
await using (FileStream stream = File.Create(path))
{
// Write the Xml declaration :
xml.WriteStartDocument();
// Serialize the object graph to the stream :
foreach (Categories c in cats)
{
// Write a root element :
xml.WriteStartElement("category");
foreach(Products p in c.Products)
{
xml.WriteElementString("product", p.ProductName);
}
// Write the closing root element :
xml.WriteEndElement();
xml.Flush();                        
}
// CLose the helper and stream :
xml.Close();
xmlFileStream.Close();
}
}
}

共享的代码存在多个问题。

让我们尝试理解每个问题并思考问题的可能解决方案 -
据我所知,问题陈述是,您想创建一个 XML 文件,其中包含类别和类别下的产品。因此,为简单起见,我假设您正在尝试获取如下所示的XML文件 -

<?xml version="1.0" encoding="utf-8"?>
<categories>
<category>
<product>Chai</product>
<product>Chang</product>
<product>Guaraná Fantástica</product>
<product>Sasquatch Ale</product>
<product>Steeleye Stout</product>
<product>Côte de Blaye</product>
</category>
<category>
<product>Aniseed Syrup</product>
<product>Chef Anton's Cajun Seasoning</product>
<product>Chef Anton's Gumbo Mix</product>
<product>Grandma's Boysenberry Spread</product>
</category>
</categories>

谈到上面发布的代码 -
的问题 1:使用指定路径 -
多次创建文件

// Create a file stream :
xmlFileStream = File.Create(path);

您已经在上面行中触发了File.Create,因此当您触发以下代码时,它说文件已在使用中。(以下行不是必需的(

await using (FileStream stream = File.Create(path))

问题 2:Linq 查询不正确。您可以将 linq 查询替换为以下代码 -

var cats = db.Categories
.Include(c => c.Products).ToList();

问题 3:XML 构造错误...
您需要将类别标签包装在父类别中,因为将创建多个类别对象。同样在上面的代码中,您正在尝试在读取一个类别时刷新 xml。您需要在最后一次执行刷新

xml.WriteEndElement();

被执行。

因此,您可以替换用于创建xml的代码块,如下所示-

// Write the Xml declaration :
xml.WriteStartDocument();
xml.WriteStartElement("categories");
// Serialize the object graph to the stream :
foreach (Categories c in cats)
{
// Write a root element :
xml.WriteStartElement("category");
foreach (Products p in c.Products)
{
xml.WriteElementString("product", p.ProductName);
}
// Write the closing root element :
xml.WriteEndElement();                    
}
xml.WriteEndElement();
xml.Flush();
// CLose the helper and stream :
xml.Close();
xmlFileStream.Close();

现在应该使用类别->类别[].
和每个类别->产品[]创建文件。

谢谢

最新更新