问题描述:

I've got a windows form with save/loading of XML files and it asks the user where they want to save/load it. My problem is I dont know how to change this method to load the file from where the user wants and not where the streamreader specifies.

The code below is of my button and LoadValues Method.

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);

}

}

网友答案:

I would pass the Stream from the OpenFileDialog to LoadValues(...), and use that to construct your StreamReader:

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

and

if ((myStream = sFile1.OpenFile()) != null)
{
   using (myStream)
   {
      Values v = LoadValues(myStream);
      ...
   }
}
网友答案:

You need to pass the Stream as a parameter to your function.

相关阅读:
Top