CodexBloom - Programming Q&A Platform

XDocument Save() Method scenarios with InvalidOperationException in .NET 5 When Serializing to File Stream

👀 Views: 57 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-09
xml xdocument dotnet csharp

I'm trying to implement I've tried everything I can think of but I'm working on a personal project and I'm working with an `InvalidOperationException` when trying to save an `XDocument` to a `FileStream` in .NET 5. The code I've written looks something like this: ```csharp using System; using System.IO; using System.Xml.Linq; class Program { static void Main() { var xdoc = new XDocument( new XElement("root", new XElement("child", "content") ) ); SaveXmlToFile(xdoc, "output.xml"); } static void SaveXmlToFile(XDocument doc, string filePath) { using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None)) { doc.Save(fs); } } } ``` When I run this code, I get the following exception: ``` System.InvalidOperationException: The 'XDocument' is already in use. It want to be modified or accessed. ``` I've confirmed that the `XDocument` is not being modified elsewhere, and this is the only point where I'm trying to access it. I've also tried creating a new instance of `XDocument` just for the save operation, but that didn't resolve the scenario. The `FileStream` is properly disposed of after the save operation, so I don't think that's the question either. I'm not sure if this is a known limitation or if I'm missing something in how I'm using `XDocument`. Has anyone experienced this scenario or can suggest a way to resolve it? For context: I'm using Csharp on Linux. What's the best practice here? I'm developing on CentOS with Csharp. Has anyone dealt with something similar?