在 C# Dot Net 中,当您想要反序列化 xml 文件时如何处理异常?但默认情况下该文件不存在
在C#DOT NET中,当您要去除XML文件时如何处理异常,但是默认情况下,该文件不存在!因为您必须运行该程序才能创建一个程序。
以下是我需要帮助的领域。
public static Compare_Data[] Deserialize()
{
Compare_Data[] cm;
cm = null;
string path = @"C:\Users\XYZ\Desktop\BACKUP_DATA\log.xml";
XmlSerializer xs = new XmlSerializer(typeof(Compare_Data[]));
if (File.Exists(path))
{
using (FileStream fs = new FileStream(path, FileMode.Open))
{
// This will read the XML from the file and create the new instance of Compare_Data.
cm = (Compare_Data[])xs.Deserialize(fs);
return cm;
}
}
else
{
using (FileStream fs = new FileStream(path, FileMode.Create))
{
xs.Serialize(fs); /// what to add here ?
}
}
return null;
}
In C# Dot Net, How to handle a exception when you want to de-serialize a xml file, but by default the file doesn't exists! because you have to run the program to create one.
Below is the area where I need Help.
public static Compare_Data[] Deserialize()
{
Compare_Data[] cm;
cm = null;
string path = @"C:\Users\XYZ\Desktop\BACKUP_DATA\log.xml";
XmlSerializer xs = new XmlSerializer(typeof(Compare_Data[]));
if (File.Exists(path))
{
using (FileStream fs = new FileStream(path, FileMode.Open))
{
// This will read the XML from the file and create the new instance of Compare_Data.
cm = (Compare_Data[])xs.Deserialize(fs);
return cm;
}
}
else
{
using (FileStream fs = new FileStream(path, FileMode.Create))
{
xs.Serialize(fs); /// what to add here ?
}
}
return null;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果一般,您不希望方法具有副作用。在这种情况下,在
else
分支中创建一个空日志文件可能是不必要的,当要记录数据时,应通过单独的serialize()
方法来处理。您的代码可以简化这样的内容:
If general, you don't want your methods to have side effects. In this case, creating an empty log file in the
else
branch is probably unnecessary and should be handled by a separateSerialize()
method when there is data to be logged.Your code could be simplified something like this: