Windows窗体XML序列化保存对话框

时间:2012-05-03 10:36:28

标签: c# xml windows forms streamwriter

我坚持这种愚蠢的形式......继承我的代码。它将它保存在streamwriter想要的地方,但当我通过savedialog框保存到用户想要的地方时,它会创建XML,但不会放入任何内容!有人可以看看,因为它开始让我振作起来!

void SavebuttonClick(object sender, EventArgs e)
{
    Stream myStream ;
    SaveFileDialog savefile1 = new SaveFileDialog();

    savefile1.Filter = "xml files |*.xml"  ;
    savefile1.FilterIndex = 2 ;
    savefile1.RestoreDirectory = true ;

    if(savefile1.ShowDialog() == DialogResult.OK)
    {
        if((myStream = savefile1.OpenFile()) != null)
        {
            Values v = new Values();
            v.task1_name = this.task1_name.Text;
            v.task1_desc = this.task1_desc.Text;
            v.task1_date = this.task1_date.Value;
            v.task1_time = this.task1_time.Value;
            SaveValues(v);
        }
        myStream.Close();   
    }
}

这是节选者......

public void SaveValues(Values v)
{
    XmlSerializer serializer = new XmlSerializer(typeof(Values));
    using(TextWriter textWriter = new StreamWriter(@"E:\TheFileYouWantToStore.xml"))
    {
        serializer.Serialize(textWriter, v);
    }
...
}

编辑:

public class Values 
{
public string task1_name { get; set;}
public string task1_desc { get; set;}
public DateTime task1_date { get; set;}
public DateTime task1_time { get; set;}
}

我认为这是你所说的代码,虽然对于编码虽然相当新:但是

1 个答案:

答案 0 :(得分:0)

序列化后您必须致电textWriter.close();。如果你不关闭编写器,它将不会将chenges应用于文件。 顺便说一句,您要将值写入 E:\ TheFileYouWantToStore.xml 。您的保存保存方法不使用用户文件。

public void SaveValues(Values v)
{
    XmlSerializer serializer = new XmlSerializer(typeof(Values));
    using(TextWriter textWriter = new StreamWriter(@"E:\TheFileYouWantToStore.xml"))
    {
        serializer.Serialize(textWriter, v);
        textWriter.close();
    }
...
}

修改

if(savefile1.ShowDialog() == DialogResult.OK)
{
        Values v = new Values();
        v.task1_name = this.task1_name.Text;
        v.task1_desc = this.task1_desc.Text;
        v.task1_date = this.task1_date.Value;
        v.task1_time = this.task1_time.Value;
        SaveValues(savefile1.FileName, v);
}

-

public void SaveValues(string fileName, Values v)
{
    XmlSerializer serializer = new XmlSerializer(typeof(Values));
    using(TextWriter textWriter = new StreamWriter(fileName))
    {
        serializer.Serialize(textWriter, v);
        textWriter.close();
    }
...
}