Filestream不会编写包含OpenFileDialog项目的xmldoc

时间:2012-08-09 13:43:43

标签: c# .net filestream xmldocument openfiledialog

我有这个代码,它接受使用OpenFileDialog获取的文件路径,并尝试将其保存到xml文件中。出于某种原因,如果其中一个节点包含来自此打开文件对话框的字符串,则不会写入xml doc。不会抛出异常,应用程序不会崩溃,只是文件不会被写入。

如果我使用字符串文字代替具有相同内容的m_strSoundFile,则xml文档将被正确写入。所以它与'\'字符是非法的无关,这是我最初的想法。也许它与OpenFileDialog是Win32的事实有关?任何帮助将不胜感激。

谢谢, 亚历

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    string m_strSoundFile;

    public MainWindow()
    {
        InitializeComponent();
    }

    private void btnChooseFile_Click(object sender, RoutedEventArgs e)
    {
        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
        dlg.Filter = "Wav files (*.wav)|*.wav"; // Filter files by extension
        dlg.InitialDirectory = @"C:\windows\media";

        Nullable<bool> result = true;
        bool pathExists = false;
        do
        {
            result = dlg.ShowDialog();

            if (result == true)
            {
                pathExists = dlg.CheckPathExists;
                if (!pathExists)
                    MessageBox.Show("Path does not exist");
                else
                    m_strSoundFile = dlg.FileName;
            }

        } while (result == true && !pathExists);

        m_tbFilename.Text = m_strSoundFile;
    }

    private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        XmlDocument xmlDoc = new XmlDocument();
        XmlNode xmlRootNode = xmlDoc.CreateElement("Settings");

        XmlNode node = xmlDoc.CreateElement("File");
        XmlAttribute a = xmlDoc.CreateAttribute("Path");
        a.Value = m_strSoundFile;

        node.Attributes.Append(a);

        xmlRootNode.AppendChild(node);
        xmlDoc.AppendChild(xmlRootNode);

        System.IO.FileStream fs;
        try
        {
            fs = System.IO.File.Open("configfile.xml", System.IO.FileMode.Create, System.IO.FileAccess.Write);
            xmlDoc.Save(XmlWriter.Create(fs, new XmlWriterSettings() { Indent = true, Encoding = Encoding.UTF8 }));
            fs.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

好的,我明白了。使用文件流的绝对路径后,它工作。在不使用绝对路径时,它有条件地工作仍然很奇怪。