2009-10-05 30 views
0

一直收到 「索引超出陣列的邊界的」 上線#574錯誤是:解析字符串時索引超出數組錯誤的界限?

label.Font =新字體(fontNameFields [0],Single.Parse(fontNameFields [1]));

...下面的文本文件,我解析包含此確切信息:

Label 
"hi tyler" 
23, 76 
Arial,12.5 

...我能成功解析所有其他信息(只是沒有最後一行),和我的代碼有是:

MatchCollection lines = Regex.Matches(File.ReadAllText(Path), @"(.+?)\r\n""([^""]+)""\r\n(\d+), (\d+)"); 
foreach (Match match in lines) 
{ 
    string control = match.Groups[1].Value; 
    string text = match.Groups[2].Value; 
    int x = Int32.Parse(match.Groups[3].Value); 
    int y = Int32.Parse(match.Groups[4].Value); 
    String cfont = match.Groups[5].Value; 
    string color = match.Groups[6].Value; 

    Console.WriteLine("{0}, \"{1}\", {2}, {3}, {4}, {5}", control, text, x, y, cfont, color); 



    switch (control) 
    { 
     case "Label": 
      Label label = new Label();  

      label.Text = text; 

      label.AutoSize = true; 
      label.IsAccessible = true; 

      label.MouseClick += new MouseEventHandler(label_MouseClick); 
      label.MouseDoubleClick += new MouseEventHandler(label_MouseDoubleClick); 
      label.MouseDown += new MouseEventHandler(label_MouseDown); 
      label.MouseMove += new MouseEventHandler(label_MouseMove); 
      label.MouseUp += new MouseEventHandler(label_MouseUp); 

      label.Location = new Point(x, y); 
      canvas.Controls.Add(label); 

          String fontName = cfont; 
    String[] fontNameFields = fontName.Split(','); 


    label.Font = new Font(fontNameFields[0], Single.Parse(fontNameFields[1])); 

...我認爲有可能是有點不妥獲取字體的東西,正則表達式...我不知道,但它只是將無法正常工作,可有人請幫助?

對於這個問題的歷史,請參閱:Parsing font info and converting it to System.Drawing.Font

+0

什麼是你'Console.WriteLine'語句輸出? – 2009-10-05 13:22:13

+0

我不知道。它是一個winforms應用程序,所以沒有控制檯窗口出現。我只是忘了刪除該行 – 2009-10-05 13:23:36

+1

你在尋求幫助,但不能打擾你做自己的調試?曾聽說過'MessageBox.Show'? – 2009-10-05 13:30:25

回答

0

嘗試

@"(.+?)\r\n""([^""]+)""\r\n(\d+), (\d+)\r\n(\w+,\d+\.?\d)" 

它類似於slashmais的解決方案,只是在什麼字體而言,其大小更嚴格一點,更接近你原來的,我喜歡的原因是因爲這些塊更明確可見。

+0

謝謝你mjv - 有沒有你的正則表達式,我reallt像錯誤,但是,我仍然越來越愚蠢的出界線錯誤: label.Font = new Font(fontNameFields [0],Single.Parse( fontNameFields [1])); – 2009-10-05 13:46:08

+0

@baeltazor我沒有看到你的邏輯預計這個字體行作爲一個單一的令牌,以後分割,在程序中的Font = new Font()行之前。在一分鐘內檢查,我將相應地編輯正則表達式! – mjv 2009-10-05 14:24:59