Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP .NET Core write to XML-file

In ASP .NET Core, I am trying to add some XML-Element with attributes to an existing XML file.

In ASP NET 4.5, I would have used the code below to make this working:

string path = Server.MapPath("~/Data/foo.xml");
XDocument xdoc = XDocument.Load(path);
   //Do stuff with XElement and XAttributes...
xdoc.Save(path);

But with ASP .NET Core, I cannot use Server.MapPath(), So I get the complete path with IHostingEnvironment instead: (Read more here )

Running the complete code below on ASP .NET Core will result in "Cannot convert from String to System.IO.Stream" when trying to run "xdoc.Save(pathToDataFile);" ??

  var contentRoot = hostingEnvironment.ContentRootPath;
  string pathToDataFile = contentRoot + "\\Data\\foo.xml";
  XDocument xdoc = XDocument.Load(pathToDataFile);
    //Do stuff with XElement and XAttributes...
  xdoc.Save(pathToDataFile);

Why is "xdoc.Save()" not working in ASP .NET Core but working fine in .NET 4.5?

like image 726
Andreas Avatar asked Jan 26 '17 20:01

Andreas


2 Answers

APIs available in .NET Core are a subset of the ones available in the full .NET framework. In some areas, you'll find that pretty much everything from .NET 4.5 is available in .NET Core, but that's not always the case.

In your case, if you have a look with Visual Studio at what overloads of the Save method are available, you'll find these ones:

public void Save(Stream stream);
public void Save(TextWriter textWriter);
public void Save(XmlWriter writer);
public void Save(Stream stream, SaveOptions options);
public void Save(TextWriter textWriter, SaveOptions options);

The reason why you have a compilation error is now pretty clear. In .NET Core, there's no overload accepting a string that defines the file path where the document should be saved.

You'll have to create a write-enabled Stream pointing to the desired path first and pass that Stream to the Save method. You can have a look at the full .NET framework implementation for reference.

like image 164
Mickaël Derriey Avatar answered Nov 04 '22 20:11

Mickaël Derriey


I had the same issue, and FileStream works for me.

FileStream fileStream = new FileStream("file.xml", FileMode.Create);
XmlWriterSettings settings = new XmlWriterSettings() { Indent = true};
XmlWriter writer = XmlWriter.Create(fileStream, settings);

Remember to use the following lines of code to prevent the file from being truncated.

writer.Flush();
fileStream.Flush();
like image 24
Walter Arguello Avatar answered Nov 04 '22 22:11

Walter Arguello