And*_*eas 5 c# asp.net linq-to-xml asp.net-core
在 ASP .NET Core 中,我试图将一些带有属性的 XML 元素添加到现有的 XML 文件中。
在 ASP NET 4.5 中,我会使用下面的代码来使其工作:
string path = Server.MapPath("~/Data/foo.xml");
XDocument xdoc = XDocument.Load(path);
//Do stuff with XElement and XAttributes...
xdoc.Save(path);
Run Code Online (Sandbox Code Playgroud)
但是对于 ASP .NET Core,我不能使用 Server.MapPath(),所以我使用 IHostingEnvironment 获取完整路径:(在这里阅读更多)
当尝试运行“xdoc.Save(pathToDataFile);”时,在 ASP .NET Core 上运行以下完整代码将导致“无法从字符串转换为 System.IO.Stream”。??
var contentRoot = hostingEnvironment.ContentRootPath;
string pathToDataFile = contentRoot + "\\Data\\foo.xml";
XDocument xdoc = XDocument.Load(pathToDataFile);
//Do stuff with XElement and XAttributes...
xdoc.Save(pathToDataFile);
Run Code Online (Sandbox Code Playgroud)
为什么“xdoc.Save()”在 ASP .NET Core 中不起作用,但在 .NET 4.5 中工作正常?
小智 6
我遇到了同样的问题,FileStream 对我有用。
FileStream fileStream = new FileStream("file.xml", FileMode.Create);
XmlWriterSettings settings = new XmlWriterSettings() { Indent = true};
XmlWriter writer = XmlWriter.Create(fileStream, settings);
Run Code Online (Sandbox Code Playgroud)
请记住使用以下代码行来防止文件被截断。
writer.Flush();
fileStream.Flush();
Run Code Online (Sandbox Code Playgroud)
.NET Core 中可用的 API 是完整 .NET 框架中可用 API 的子集。在某些领域,您会发现 .NET 4.5 中的几乎所有内容都可以在 .NET Core 中使用,但情况并非总是如此。
在您的情况下,如果您使用 Visual Studio 查看该Save方法的哪些重载可用,您会发现这些:
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);
Run Code Online (Sandbox Code Playgroud)
编译错误的原因现在很清楚了。在 .NET Core 中,没有重载接受string定义文档保存路径的a 。
您必须首先创建一个Stream指向所需路径的写启用,然后将其传递Stream给Save方法。您可以查看完整的 .NET 框架实现以供参考。
| 归档时间: |
|
| 查看次数: |
10524 次 |
| 最近记录: |