上篇写了读取xml简单的方法,但是比较麻烦,所以优化了一下,通过序列化来读取配置文件.
xml格式:
<?xml version="1.0"?>
<StatsConfigTwo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<statsDate>2018-07-19T15:33:41.0708883+08:00</statsDate>
<readBarTotalCount>3</readBarTotalCount>
<readBarSuccessCount>3</readBarSuccessCount>
<readBarFailCount>3</readBarFailCount>
<writeTagTotalCount>3</writeTagTotalCount>
<writeTagSuccessCount>3</writeTagSuccessCount>
<writeTagFailCount>3</writeTagFailCount>
<checkTagTotalCount>3</checkTagTotalCount>
<checkTagSuccessCount>3</checkTagSuccessCount>
<checkTagFailCount>3</checkTagFailCount>
</StatsConfigTwo>
代码:
[Serializable]
public class StatsConfigTwo
{
[XmlElement]
public DateTime statsDate = DateTime.MinValue;
[XmlElement]
public int readBarTotalCount { get; set; }
[XmlElement]
public int readBarSuccessCount { get; set; }
[XmlElement]
public int readBarFailCount { get; set; }
[XmlElement]
public int writeTagTotalCount { get; set; }
[XmlElement]
public int writeTagSuccessCount { get; set; }
[XmlElement]
public int writeTagFailCount { get; set; }
[XmlElement]
public int checkTagTotalCount { get; set; }
[XmlElement]
public int checkTagSuccessCount { get; set; }
[XmlElement]
public int checkTagFailCount { get; set; }
public static bool ReadFile(string path,out StatsConfigTwo config)
{
if (!File.Exists(path))
{
config = new StatsConfigTwo();
WriteFile(path, config);
}
using (Stream s = File.OpenRead(path))
{
try
{
XmlSerializer xml = new XmlSerializer(typeof(StatsConfigTwo));
config = (StatsConfigTwo)xml.Deserialize(s);
return true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
config = null;
return false;
}
}
}
public static void WriteFile(string path, StatsConfigTwo config)
{
using (Stream s = File.OpenWrite(path))
{
try
{
XmlSerializer xml = new XmlSerializer(typeof(StatsConfigTwo));
xml.Serialize(s, config);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
s.Close();
}
}