patterncsharpMinor
Reading a configuration file in c#
Viewed 0 times
readingfileconfiguration
Problem
The configuration file of my app is similar to,
Just trying to read the above small configuration file and I wrote this method.
-
Where should I use
-
Is this an overkill for reading this simple xml file?
Just trying to read the above small configuration file and I wrote this method.
public static class Configuration
{
public static T DeSerialize(string filePath)
{
if (!System.IO.File.Exists(filePath))
{
throw new System.IO.FileNotFoundException(filePath);
}
var serializer = new System.Xml.Serialization.XmlSerializer(T);
return (T)serializer.Deserialize(new FileStream(filePath, FileMode.Open));
}
}-
Where should I use
using in this code? (Because, I never ever dispose the new FileStream that I wrote in this method)-
Is this an overkill for reading this simple xml file?
Solution
-
I would definitely wrap the FileStream object into a using clause like this:
This way the Dispose method of the
Also note that you have to use
-
My opinion is that it is overkill to create a generic method if you have only one kind of configuration file in your app. This method might be hard to read for a maintainer who is not sufficiently comfortable with generics and it has no benefit in making your code DRY-er if you have only one type of configuration file.
I would definitely wrap the FileStream object into a using clause like this:
using (Stream reader = new FileStream(filePath, FileMode.Open))
{
var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
return (T)serializer.Deserialize(reader);
}This way the Dispose method of the
FileStream gets called immediately. Otherwise it will be delayed until the FileStream object gets garbage collected. This may not be a big problem in practice in simple applications where you read the configuration only once but is good practice to do it anyway.Also note that you have to use
XmlSerializer(typeof(T)) instead of XmlSerializer(T).-
My opinion is that it is overkill to create a generic method if you have only one kind of configuration file in your app. This method might be hard to read for a maintainer who is not sufficiently comfortable with generics and it has no benefit in making your code DRY-er if you have only one type of configuration file.
Code Snippets
using (Stream reader = new FileStream(filePath, FileMode.Open))
{
var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
return (T)serializer.Deserialize(reader);
}Context
StackExchange Code Review Q#40434, answer score: 3
Revisions (0)
No revisions yet.