【问题标题】:Saving a textbox url to an XML file using a button in C# Winforms使用 C# Winforms 中的按钮将文本框 url 保存到 XML 文件
【发布时间】:2018-07-24 13:43:27
【问题描述】:

我希望保存 XML 文件的路径,并在程序重新打开时使用 Winforms 上的按钮加载它。我已经环顾了一下保存状态,但到目前为止似乎没有什么可以减少芥末。 下面是我的代码

    private void Form1_Load(object sender, EventArgs e)
    {
        //Loading of the form 

    }
    private void btnOpen_Click(object sender, EventArgs e)
    {
        using (FolderBrowserDialog fbd = new FolderBrowserDialog()  { Description="Select your folder"})
        {
            if (fbd.ShowDialog() == DialogResult.OK)
                webBrowser.Url = new Uri(fbd.SelectedPath);
            txtPath.Text = fbd.SelectedPath;
            // Button used to open the folder explorer and display file path in the text box. 
        }
    }

    private void btnBack_Click(object sender, EventArgs e)
    {
        if (webBrowser.CanGoBack)
            webBrowser.GoBack(); //Sends the explorer back one page providing there is a page to go back too
    }
    private void btnForward_Click(object sender, EventArgs e)
    {
        if (webBrowser.CanGoForward)
            webBrowser.GoForward(); //Sends the explorer forward one page providing there is a page to go forward too

    }

    private void btnSave_Click(object sender, EventArgs e)
    {

    }

    private void txtPath_TextChanged(object sender, EventArgs e)
    {

    }       
}

The save search is what I want to use to store the users chosen path.

【问题讨论】:

标签: c# xml winforms file explorer


【解决方案1】:

@kurdy 已经评论了这个的首选方法;使用用户设置。

直接使用 Xml 实际上有点困难,尤其是如果您是初学者。 无论如何,我会尝试解释它,因为您的问题是关于 XML。

这是您可以使用 Xml 保存它的方法,不要忘记 using System.Xml;using System.IO;

        var myString = "Some string to save to XML"; // Some string to save into the xml file
        var mySavePath = @"C:\dontSaveToCRoot.xml";  // Edit this path or save it next to your exe
        var xml = new XmlDocument();                 // Create a instance of XmlDocument


        if (File.Exists(mySavePath)) // Load up the XmlDocument from file if it exists
        {
            xml.Load(mySavePath);    // Load it from the specified path
        }
        else                         // Or provide the default xml if no file exists yet.
        {
            xml.LoadXml("<root />"); // Add a <root/> element as the DocumentElement
        }

        // store your string in the xml document, by adding it as an attribute to the <root /> element
        // results in: <root my-string="myString contents" />
        xml.DocumentElement.SetAttribute("my-string", myString);

        xml.Save(mySavePath);       // Save the Xml back to the specified path.

【讨论】:

    猜你喜欢
    • 2014-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多