XML文件讀寫操作導致數據全部丟失

losedguest 2017-12-04 11:59:36
用一個XML文檔存取一些簡單的數據和日期,在客戶端經常出現文檔空白導致Root缺失錯誤(整個XML文檔里的數據全部丟失)
不知道以下的寫法有啥問題?求大神們幫忙看看
正常情況下測試始終測試不出來

方法很簡單

public class PubNodes
{
private string NodeFileName = "Nodes.memorizer";

private string SubForder = "PubNodes";

private string NodePath = "";

private string RootName = "NodeList";

private XmlDocument XMLFile;

private XmlNode LayoutRoot;

public PubNodes()
{
this.NodePath = PubFile.CombileFile(PubFile.GetBasePath(), this.SubForder);
if (!System.IO.Directory.Exists(this.NodePath))
{
System.IO.Directory.CreateDirectory(this.NodePath);
}
this.NodePath = PubFile.CombileFile(this.NodePath, this.NodeFileName);
if (!System.IO.File.Exists(this.NodePath))
{
this.XMLFile = new XmlDocument();
}
else
{
this.XMLFile = new XmlDocument();
this.XMLFile.Load(this.NodePath);
}
this.ReadXML();
}

private void ReadXML()
{
try
{
if (!this.XMLFile.HasChildNodes)
{
XmlDeclaration newChild = this.XMLFile.CreateXmlDeclaration("1.0", "utf-8", null);
this.XMLFile.AppendChild(newChild);
this.LayoutRoot = this.XMLFile.CreateElement(this.RootName);
this.XMLFile.AppendChild(this.LayoutRoot);
}
else
{
this.LayoutRoot = this.XMLFile.SelectSingleNode(this.RootName);
}
}
catch (System.Exception ex)
{
throw ex;
}
}

/// <summary>
/// 節點字母+數字格式,存值
/// </summary>
/// <param name="NodeName">節點</param>
/// <param name="NodeValue">值</param>
public void SaveNode(string NodeName, string NodeValue)
{
try
{
XmlNode xmlNode = this.LayoutRoot.SelectSingleNode(NodeName);
if (xmlNode == null)
{
xmlNode = this.XMLFile.CreateNode(XmlNodeType.Element, NodeName, "");
xmlNode.InnerText = NodeValue;
this.LayoutRoot.AppendChild(xmlNode);
}
else
{
xmlNode.InnerText = NodeValue;
}
this.XMLFile.Save(this.NodePath);
}
catch (System.Exception ex)
{
throw ex;
}
}
/// <summary>
/// 取值
/// </summary>
/// <param name="NodeName">節點</param>
/// <returns></returns>
public string GetNode(string NodeName)
{
string result = "";
try
{
XmlNode xmlNode = this.LayoutRoot.SelectSingleNode(NodeName);
if (xmlNode != null)
{
result = xmlNode.InnerText;
}
}
catch (System.Exception ex)
{
File.Delete(this.NodePath);//報錯刪除原文件
throw ex;

}
return result;
}
}
...全文
173 2 点赞 打赏 收藏 举报
写回复
2 条回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
相关推荐
发帖
C#
加入

10.6w+

社区成员

.NET技术 C#
申请成为版主
帖子事件
创建了帖子
2017-12-04 11:59
社区公告

让您成为最强悍的C#开发者