这真的很奇怪。我正在编写一个编写XML文件的应用程序。但在某些情况下,文件不会被创建/覆盖。
我设法追踪导致它无法写入所需的特定事件,并将其分离为独立程序:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
bool doFileOpenFirst = false;
if (doFileOpenFirst)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.CheckFileExists = true;
dialog.Filter = "Image files|*.bmp;*.jpg;*.png";
dialog.ShowDialog();
}
// Just write a trivial XML file
XmlDocument doc = new XmlDocument();
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(dec);// Create the root element
XmlElement root = doc.CreateElement("Database");
doc.AppendChild(root);
doc.Save("Trivial.xml");
}
}
现在如果你运行它,你会发现它最初有效。 现在让doFileOpenFirst为true。在编写XML之前,它会显示一个用于打开文件的对话框。 如果使用此对话框选择文件(任何文件; 不“Trivial.xml”),则之后的XML Save将失败。默默。 如果在OpenFileDialog中单击取消,则保存将正常工作。
所以这里的文件句柄存在一些问题,但是解决方法是什么?您将看到强制OpenFileDialog的Dispose无效。
答案 0 :(得分:1)
我认为你应该放置这些打开对话框的代码并将xml保存到Form的Load Event中。
答案 1 :(得分:1)
您的对话框(OpenFileDialog)和您的XML保存代码彼此独立。因此,显示对话框不会导致XML保存问题,尤其是在对话框中选择其他文件时。
另外,为了帮助您,我已经检查了您的代码和步骤,无论如何,无论是否使用OpenFileDialog,XML都在保存。因此,假设您的问题不是来自打开文件对话框。在您提供的示例中没有问题。
答案 2 :(得分:1)
似乎工作正常!我试着按原样工作。
打开随机图像文件没有问题:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
namespace StackOverflow
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
bool doFileOpenFirst = true;
if (doFileOpenFirst)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.CheckFileExists = true;
dialog.Filter = "Image files|*.bmp;*.jpg;*.png";
dialog.ShowDialog();
}
// Just write a trivial XML file
XmlDocument doc = new XmlDocument();
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(dec);// Create the root element
XmlElement root = doc.CreateElement("Database");
doc.AppendChild(root);
doc.Save("Trivial.xml");
}
}
}