OpenFileDialog で取得したファイル パスを受け取り、それを xml ファイルに保存しようとするこのコードがあります。ノードの 1 つにこのファイルを開くダイアログからの文字列が含まれていると、何らかの理由で xml ドキュメントが書き込まれません。例外はスローされず、アプリはクラッシュしません。ファイルが書き込まれないだけです。
同じ内容の 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);
}
}
}