2010-04-20 131 views
1

我創建了一個使用.NET 3.5編譯的應用程序。並使用了FolderBrowserDialog對象 。當按下按鈕時,我執行以下代碼:文件夾瀏覽對話框沒有顯示文件夾

FolderBrowserDialog fbd = new FolderBrowserDialog(); 
fbd.ShowDialog(); 

顯示文件夾對話框,但我看不到任何文件夾。我只看到 是按鈕OK &取消(並且當 ShowNewFolderButton properyty設置爲true時創建新文件夾按鈕)。當我嘗試完全相同的 不同形式的代碼時,一切正常。

任何想法??

回答

1

檢查運行對話框的線程是否在STAThread上。因此,例如,請確保您的Main方法標有[STAThread]屬性:

[STAThread] 
static void Main() { 
    Application.EnableVisualStyles(); 
    Application.SetCompatibleTextRenderingDefault(false); 
    Application.Run(new Form1()); 
} 

否則,你可以(在FolderBrowserDialog Class從社區內容)做到這一點。

/// <summary> 
/// Gets the folder in Sta Thread 
/// </summary> 
/// <returns>The path to the selected folder or (if nothing selected) the empty value</returns> 
private static string ChooseFolderHelper() 
{ 
    var result = new StringBuilder(); 
    var thread = new Thread(obj => 
    { 
     var builder = (StringBuilder)obj; 
     using (var dialog = new FolderBrowserDialog()) 
     { 
      dialog.Description = "Specify the directory"; 
      dialog.RootFolder = Environment.SpecialFolder.MyComputer; 
      if (dialog.ShowDialog() == DialogResult.OK) 
      { 
       builder.Append(dialog.SelectedPath); 
      } 
     } 
    }); 

    thread.SetApartmentState(ApartmentState.STA); 
    thread.Start(result); 

    while (thread.IsAlive) 
    { 
     Thread.Sleep(100); 
     } 

    return result.ToString(); 
} 
+0

非常有幫助。謝謝! – chessofnerd 2012-05-29 16:51:48

相關問題