简体   繁体   English

尝试使用 C# 从文件读取和写入时 WPF 出错

[英]Error in WPF when trying to read and write from a file using C#

So I am trying to read and write from/in .xml file and I get this error:所以我试图从/在 .xml 文件中读取和写入,但出现此错误:

'System.Xml.Linq.XDocument' does not contain a definition for 'load' and no extension method 'load' accepting a first argument of type 'System.Xml.Linq.XDocument' could be found (are you missing a using directive or an assembly reference?) 

for line:对于线:

document.load("MyXmlFile.xml");

Code Sample:代码示例:

using System.Xml.Linq;      // I included this for XDocument
using System.Xml.XPath;     // I included this because I thought it will fix a problem

public partial class MainWindow : Window
{
    public MainWindow() => InitializeComponent();

    public void LoadXML()
    {
        var document = new XDocument();

        if (!File.Exists("MyXmlFile.xml"))
             document.Save("MyXmlFile.xml");
        else document.load("MyXmlFile.xml");
    }
}

You have to change your method a little:你必须稍微改变你的方法:

if (!File.Exists("MyXmlFile.xml"))
{
    document.Save("MyXmlFile.xml");
}
else
{
    //We know it exists so we can load it
    document = XDocument.Load("MyXmlFile.xml"); // changed
}

//Continue to work with document

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 C#、WPF 中的相对路径读取/写入文件? - How to read/write a file from a relative path in C#, WPF? C#WPF和Sqlite:当尝试从sqlite数据库表中读取数据时,Datagrid显示最后一个表记录 - C# WPF and Sqlite: Datagrid displays last table recording when trying to read from an sqlite database table 我在 C# 的 windows 服务无法写入文件,同时另一个 C# 应用程序正在尝试读取文件 - My windows service in C# cannot write to file, when at the same time another C# app is trying to read the file 尝试使用JObject从文件解析json时出现C#asp.net错误 - C# asp.net error when trying to parse json from a file using JObject 如何在C#WPF中使用Datarow写入Excel文件 - How to write to excel file using Datarow in C# Wpf 通过C#从文本文件读取数据并将结果写入文本文件时出错 - Error in read data from text file and write result in a text file by C# 尝试在Windows Phone 8应用中写入然后读取XML文件时出错 - Error when trying to write then read a XML file in Windows Phone 8 app 如何使用内存映射文件C#读写文件? - How to read and write a file using Memory Mapped File C#? 如何在WPF C#中使用xmldataprovider读取xml文件 - How to read an xml file using xmldataprovider in wpf C# 尝试通过 C# 互操作保存只读 Excel 文件时出错 - Error when trying to save read-only Excel file through C# Interop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM