C#在Closing问题中将数据保存到磁盘 [英] C# saving data to disk within Closing problem
本文介绍了C#在Closing问题中将数据保存到磁盘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好,我的WPF应用程序中存在以下问题:
我想将应用程序数据保存到磁盘。我想在主窗口Closing事件中这样做。
代码:
Hello, I have following problem in my WPF app:
I want to save application data to disk. I am trying to do this in main window Closing event.
Code:
XmlDocument Doc = new XmlDocument();
XmlElement root = Doc.CreateElement("fileset");
foreach(FileModel file in set)
{
XmlElement fileElem = Doc.CreateElement("file");
root.AppendChild(fileElem);
fileElem.SetAttribute("path", file.Path);
}
System.IO.File.Create(path);
using (System.IO.StreamWriter file = new System.IO.StreamWriter(path, true))
{
System.IO.StringWriter sw = new System.IO.StringWriter();
XmlTextWriter tx = new XmlTextWriter(sw);
Doc.WriteTo(tx);
file.Write(tx.ToString());
}
// Doc.Save(path);
问题导致新的System.IO.StreamWriter(path,true)
( Doc.Save(路径)
),永远不会返回。主窗口变黑,我必须使用taskmanager杀死app。 System.IO.File.Create(path);
工作正常。
有什么想法吗?
Problem is causing new System.IO.StreamWriter(path, true)
(Doc.Save(path)
as well), which never returns. Main window gets black and I have to kill app using taskmanager. System.IO.File.Create(path);
works fine.
Any ideas?
推荐答案
丢掉行System.IO.File.Create(path);
- 它没用了。
Throw away the lineSystem.IO.File.Create(path);
- it's useless.
XmlWriterSettings xmlSettings = new XmlWriterSettings();
xmlSettings.Encoding = System.Text.Encoding.UTF8;
xmlSettings.Indent = true;
xmlSettings.NewLineHandling = NewLineHandling.None;
xmlSettings.NewLineOnAttributes = false;
XmlWriter writer = XmlWriter.Create(path, xmlSettings);
writer.WriteStartDocument(true);
Doc.WriteTo(writer);
writer.WriteEndDocument();
writer.Close();
这篇关于C#在Closing问题中将数据保存到磁盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文