2013-07-14 36 views
2

在我的Form1事件中,並非所有事情都已完成。只有第一行被實際執行。Form1加載事件只執行第一條語句

private void Form1_Load(object sender, EventArgs e) 
    { 
     //Save the currentUser text document's contents into the currentUser string 
     System.IO.StreamReader file = new System.IO.StreamReader("C\\Users\\WoopyCat\\AppData\\Roaming\\.minecraft\\currentUser.txt"); 
     currentUser = file.ReadLine(); 

     //Save the currentUser into the textbox 
     TBcurrentUser.Text = "The current user is " + currentUser + "."; 

     //Set the default text for the textbox 
     TBchangeTo.Text = "Whose Minecraft folder are you switching to?"; 

     //Add the default two items to the listbox 
     LBfiles.Items.Add("Minecraft folders:" + Environment.NewLine); 
     LBfiles.Items.Add("---------------------------------------------------------------------------------------------------------------------------"); 

     //Create the directory if it doesn't exist 
     if (!Directory.Exists("C:\\Users\\WoopyCat\\AppData\\Roaming\\" + folderName)) 
     { 
      Directory.CreateDirectory("C:\\Users\\WoopyCat\\AppData\\Roaming\\" + folderName); 
     } 

     //Set the default instructions in the textbox 
     TBinstructions.Text = instructions; 

     //Add each directory to the listbox 
     foreach (string value in Directory.GetDirectories("C:\\Users\\WoopyCat\\AppData\\Roaming\\" + folderName)) 
     { 
      //Remove the file location from the string 
      each = value.Replace("C:\\Users\\WoopyCat\\AppData\\Roaming\\.MCSwitcher\\", ""); 
      LBfiles.Items.Add(each + Environment.NewLine); 
     } 
    } 

表單加載時沒有任何反應。如果我添加第一行,那麼它實際上發生。就像我在這個事件中將消息框稱爲第一行一樣,它就會發生。但是這段代碼沒有任何內容。

+1

你試圖把你的代碼在構造函數中,相反,右後'的InitializeComponent();'? – tinstaafl

+0

好的,那有效。非常感謝! – TheUnrealMegashark

+2

你的代碼遇到了異常,而.Net只是吞下了異常,所以它看起來像在方法中間停止運行。見http://stackoverflow.com/questions/3209706/why-the-form-load-cant-catch-exception – tia

回答

2

變化

System.IO.StreamReader file = new System.IO.StreamReader("C\\Users\\WoopyCat\\AppData\\Roaming\\.minecraft\\currentUser.txt"); 

System.IO.StreamReader file = new System.IO.StreamReader("C:\\Users\\WoopyCat\\AppData\\Roaming\\.minecraft\\currentUser.txt"); 

你忘了結腸