Monday, November 25, 2013

Using Methods and Classes

Hi Joe,




I didn't quite understand what is the problem... at some point the variable "fileName" gets the value "mydoor.cfgmydoor.cfg", is that it?


I made a little change to better support relative paths... try it.



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 = Path.GetFullPath(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.
fileName = fileName == null ? _fileName : Path.GetFullPath(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.
fileName = fileName == null ? _fileName : Path.GetFullPath(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();
}
}
}





Best regards,


Fernando Rocha


No comments:

Post a Comment