I have an application that allows the user to retrieve partial data in json or xml depending on which radio button is selected, the data is parsed and then displayed in some Window Application Form controls. They have the option to save the data inside the controls in either a Text file or in a XML file depending on which (the same radio buttons used to retrieve data) radio button they select.
Every time I save a file, regardless which radio button is selected, it doesn't save it in the format chosen. When I check the file on my computer, it just shows a blank document icon with the type "File."
My code looks similar to this and it's inside a button:
SaveFileDialog newData = new SaveFileDialog();
if (newData.ShowDialog() == DialogResult.OK)
{
if (jsonRB.Checked)
{
newData.DefaultExt = "txt";
string dataPath = newData.FileName;
using (StreamWriter newFile = new StreamWriter(File.Create(dataPath)))
{
//Writing string to save data
}
}
else
{
newData.DefaultExt = "xml";
XmlWriterSettings adjust = new XmlWriterSettings();
adjust.ConformanceLevel = ConformanceLevel.Document;
adjust.Indent = true;
using (XmlWriter newFile = XmlWriter.Create(newData.FileName, adjust))
{
//writing data
newFile.WriteEndElement();
}
}
}
This should do the trick:
SaveFileDialog saveDlg = new SaveFileDialog();
if(jsonRB.Checked)
{
//The default selected extension
saveDlg.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
//this is used if you select All files (*.*) but omit a extension
saveDlg.DefaultExt = "txt";
}
else
{
saveDlg.Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.*";
saveDlg.DefaultExt = "xml";
}
if(saveDlg.ShowDialog() == DialogResult.OK)
{
if (jsonRB.Checked)
{
//Save JSON
}
else
{
//Save XML
}
}