I have to process an XML file (I am choosing a file with OpenFileDialog [code not present here] and when I click the second button the XML is processed to show a tree structure of that XML that has to be saved in the other file). But when I use SaveFileDialog , I want to enter a file name of the file which does not exist yet. How should I do that if I enter the filename that does not exits , an empty file will be created ?
private void button2_Click(object sender, EventArgs e)
{
SaveFileDialog fDialog = new SaveFileDialog();
fDialog.Title = "Save XML File";
fDialog.FileName = "drzewo.xml";
fDialog.CheckFileExists = false;
fDialog.InitialDirectory = @"C:\Users\Piotrek\Desktop";
if (fDialog.ShowDialog() == DialogResult.OK)
{
MessageBox.Show(fDialog.FileName.ToString());
}
string XMLdrzewo = fDialog.FileName.ToString();
XDocument xdoc = XDocument.Load(XMLdrzewo);
//// some code processing xml file
/// not ready yet, have to write to that file the tree
//structure of selected XML file
textBox2.Text = File.ReadAllText(XMLdrzewo);
When file does not exist I get FileNotFoundException was unhandled.
the code that creates your filename should be inside the if statement.
if (fDialog.ShowDialog == DialogResult.OK)
{
}
Then, you need to create a file first, eg var stream = File.Create(filename)
. Then you can fill that file with the "to be created stuff" and store the xml part in your newly created file.
Something like:
if (fDialog.ShowDialog() == DialogResult.OK)
{
using (var newXmlFile = File.Create(fDialog.FileName);
{
var xd = new XmlDocument();
var root = xd.AppendChild(xd.CreateElement("Root"));
var child = root.AppendChild(xd.CreateElement("Child"));
var childAtt = child.Attributes.Append(xd.CreateAttribute("Attribute"));
childAtt.InnerText = "My innertext";
child.InnerText = "Node Innertext";
xd.Save(newXmlFile);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.