I'm new to C# and would like to create a WPF app with xml config file. I have a certain setting file written by using System.Xml.Linq;
.
And I'd like to write else
block to read data from the file if it exists. I'm a static struct instead of class.
public struct Settings {
public static int firstParam { get; set; }
public static int secondParam { get; set; }
public static void Initialize()
{
loadFromFile();
}
public static void loadFromFile()
{
if (!File.Exists(@"./config.xml"))
{
//Write file with default values
setDefault();
XElement fP = new XElement("firstParam");
XElement sP = new XElement("secondParam");
fp.Value = firstParam.ToString();
sp.Value = secondParam.ToString();
XElement root = new XElement("settings", fp, sp);
new XDocument(root).Save(@"./config.xml");
}
else
{
//Read the existed file and set
}
}
private static void setDefault()
{
firstParam = 5;
secondParam = 5;
}
}
I found that there's a lot of outdated info about this on the StackOverFlow. Also there are XML tutorials that are teaching how to read bunch of same xml objects via foreach loops or Linq and I feel like they're not suitable for my issue. So there's a question I'd like to ask:
Is there a more suitable way in 2016 to read/write xml settings files like this one:
<?xml version="1.0" encoding="utf-8"?>
<settings>
<firstParam>5</firstParam>
<secondParam>5</secondParam>
</settings>