0

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.

4

3 回答 3

1

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;
    }
}
于 2009-11-12T20:39:59.213 回答
1

Jon Skeet 已经回答了您的第一个问题,所以对于您的第二个问题(如何将字体大小解析为浮点数):

float.Parse(s, CultureInfo.InvariantCulture);

其中 s 是包含字体大小的字符串。

于 2009-11-12T20:45:52.600 回答
1

您可能还会遇到数据转换问题:Split() 方法返回一个字符串数组,但 TextSize 是一个浮点数,而 TextStyle 是一个枚举(FontStyle)。虽然我们人类可以很容易地看出数字 12 和字符串“12”至少是相关的,但编译器要挑剔得多。

你可以试试这个 TextSize:

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

处理 TextStyle 可能有点棘手,因为您必须将字符串值与不同的枚举值进行比较。例如,要检测“粗体”样式,您可以编写:

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

干杯! 卑微的程序员,,,^..^,,,

于 2009-11-12T20:46:12.883 回答