views:

54

answers:

3

Hello,

I'm building a application that uses a file to configure some fonts. It's like this:

Font = Verdana
Size = 12
Style = Bold

And my code is like this:

openDialog.ShowDialog();
string file = openDialog.FileName;
StreamReader reader = new StreamReader(file);
while (reader.Peek() <= 0)
{
    string line = reader.ReadLine();
    string[] data = Split(new[] { '=' });
    // property is in data[0]
    // value is in data[1]
    TextFont = data[1];
    TextSize = data[3];
    TextSt = data[5];
}
reader.Close();
reader.Dispose();

And using it like this:

textBox1.Font = new System.Drawing.Font(TextFont, 12F, FontStyle.Bold);

But when I execute it I got this error:

ArgumentException

Value does not fall within the expected

Then I have two questions:

  • How can I solve this problem?
  • How can I use instead of a string for TextSize use a float to implement it in the Font method?

Thanks.

+1  A: 

You're reading a single line, but then trying to take three values from it. Look at the comment:

// property is in data[0]
// value is in data[1]

You're then using data[1], data[3] and data[5]...

You probably want something like:

openDialog.ShowDialog();
string file = openDialog.FileName;
string[] lines = File.ReadAllLines(file);
foreach (string line in line)
{
    string[] data = line.Split('=');
    string property = data[0].Trim();
    string value = data[1].Trim();
    switch (property)
    {
        case "Font": TextFont = value; break;
        case "Size": TextSize = value; break;
        case "Style": TextSt = value; break;
        default:
          // Whatever you want to do here for properties you don't recognise
          break;
    }
}
Jon Skeet
Thanks Jon Skeet, you're the guy!
Nathan Campos
+1  A: 

Jon Skeet already answered your first question, so for your second one (how to parse the font size as a float):

float.Parse(s, CultureInfo.InvariantCulture);

where s is the string containing the font size.

Brian Schroth
Thanks to answer my second question Brian.
Nathan Campos
+1  A: 

You may also have data conversion issues: the Split() method returns an array of strings, but TextSize is a float, while TextStyle is an enumeration (FontStyle). While we as human beings can easily tell that the number 12 and the string "12" are at least related, compilers are a lot pickier.

You might try this for the TextSize:

float fSize;
if (float.TryParse(data[3], out fSize))
    TextSize = fSize;

Handling the TextStyle might be a little trickier, because you'll have to compare the string value against the different enumerated values. For example, to detect the "Bold" style, you would write:

if (String.Compare("Bold", data[5]) == 0)  // true if equal
    TextStyle = FontStyle.Bold;

Cheers! Humble Programmer ,,,^..^,,,

Lee Neuse
Thanks to answer my second question Lee.
Nathan Campos