Hi Joe,
Classes should be used to separate functional modules, at least that is one of the good use of classes.
In this case, I would make a class to deal with the whole configuration part, something like:
public class ConfigurationInfo
{
// The configuration file name to load/save.
private readonly string _fileName;
public string BbsName { get; set; }
public string SysOpName { get; set; }
public bool Logs { get; set; }
public int AdminAccess { get; set; }
public int UserAccess { get; set; }
public ConfigurationInfo(string fileName)
{
_fileName = fileName;
// You can set default values.
BbsName = "BBS Name";
SysOpName = "Sysop Name";
Logs = true;
AdminAccess = 99;
UserAccess = 10;
}
public void Load(string fileName = null)
{
// If the parameter is not specified, use the default.
if (fileName == null) fileName = _fileName;
using (StreamReader streamReader = File.OpenText(fileName))
{
BbsName = streamReader.ReadLine();
SysOpName = streamReader.ReadLine();
Logs = String.Equals("Y", streamReader.ReadLine(), StringComparison.OrdinalIgnoreCase);
AdminAccess = Convert.ToInt32(streamReader.ReadLine());
UserAccess = Convert.ToInt32(streamReader.ReadLine());
streamReader.Close();
}
}
public void Save(string fileName = null)
{
// If the parameter is not specified, use the default.
if (fileName == null) fileName = _fileName;
if (!File.Exists(fileName))
{
// Gets the parent directory path.
var directoryPath = Path.GetDirectoryName(fileName);
if (directoryPath == null) return;
// Creates the specified directory and all parent directories.
Directory.CreateDirectory(directoryPath);
}
// Saves the configuration to the specified file.
using (StreamWriter streamWriter = File.CreateText(fileName))
{
streamWriter.WriteLine(BbsName);
streamWriter.WriteLine(SysOpName);
streamWriter.WriteLine(Logs ? "Y" : "N");
streamWriter.WriteLine(AdminAccess);
streamWriter.WriteLine(UserAccess);
streamWriter.Close();
}
}
}
And then you can easily save/load the configuration anywhere, for instance:
static void Main(string[] args)
{
// Save the configuration.
var configInfo1 = new ConfigurationInfo(@".\Sample.txt");
configInfo1.BbsName = "Some other name than the default";
configInfo1.Save();
var configInfo2 = new ConfigurationInfo(@".\Sample.txt");
configInfo2.Load();
Console.WriteLine("BBS Loaded: " + configInfo2.BbsName);
Console.ReadKey();
}
This saves the configuratio with a specific BBSName.
After that, it loads it to other variable and you can see that it loads great.
Is this what you were looking for?
Best regards,
Fernando Rocha
No comments:
Post a Comment