Search code examples
c#exceptionfile-iowindows-mobile-5.0

Value Doesn't Fall Within The Expected


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.


Solution

  • 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 ,,,^..^,,,