Windows窗体XML序列化加载对话框

时间:2012-05-06 23:23:33

标签: c# xml windows forms loading

我有一个带有保存/加载XML文件的窗体,它询问用户他们想要保存/加载它的位置。我的问题是我不知道如何更改此方法以从用户想要的位置加载文件而不是流读取器指定的位置。

下面的代码是我的按钮和LoadValues方法。

private void Edittask_loadbuttonClick(
    object sender, EventArgs e)
{
    Stream myStream = null;
    var sFile1 = new OpenFileDialog();

    sFile1.InitialDirectory = "c:\\";
    sFile1.Filter = "xml files (*.xml)|*.xml";
    sFile1.FilterIndex = 2;
    sFile1.RestoreDirectory = true;

    if (sFile1.ShowDialog() == DialogResult.OK)
    {
        try
        {
            if ((myStream = sFile1.OpenFile()) != null)
            {
                using (myStream)
                {
                    var v = LoadValues();
                    this.load_task1_name.Text =
                        v.task1_name;
                    this.load_task1_desc.Text =
                        v.task1_desc;
                    this.load_task1_date.Value =
                        v.task1_date;
                    this.load_checkbox.Checked =
                        v.task1_checkbox;
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(
                "Error: Could not read file from disk. Original error: " +
                ex.Message);
        }
    }
}

public Values LoadValues()
{
    var serializer = new XmlSerializer(typeof (Values));
    using (
        TextReader textReader = new StreamReader(
                                    "E:\\hello.xml")
    )
    {
        return
            (Values) serializer.Deserialize(textReader);
    }
}

2 个答案:

答案 0 :(得分:1)

我会将Stream从OpenFileDialog传递到LoadValues(...),并使用它来构建StreamReader:

public Values LoadValues(Stream stream)
{
   XmlSerializer serializer = new XmlSerializer(typeof(Values));
   using (TextReader textReader = new StreamReader(stream))
   {
      return (Values)serializer.Deserialize(textReader);
   }
}

if ((myStream = sFile1.OpenFile()) != null)
{
   using (myStream)
   {
      Values v = LoadValues(myStream);
      ...
   }
}

答案 1 :(得分:0)

您需要将Stream作为参数传递给您的函数。