簡體   English   中英

無法導入Microsoft.win32.OpenFileDialog

[英]Cannot import Microsoft.win32.OpenFileDialog

我無法使用Win32 OpenFileDialog類

我嘗試了下面的示例代碼,我將這些示例代碼直接從Microsoft文檔復制粘貼到了我的方法中,但出現了錯誤CS0246,因為編譯器找不到OpenFileDialog。

我試圖添加對Win32的引用,但無處可尋。

順便說一句,我確實嘗試過使用.NET OpenFileDialog和FolderBrowserDialog類,但是它們無法打開帶有開始位置的文件夾,並且該選項對於我的應用程序是絕對必要的。

我做錯了什么 ?

這是我的代碼。

// Configure open file dialog box
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".txt"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension

// Show open file dialog box
Nullable<bool> result = dlg.ShowDialog();

// Process open file dialog box results
if (result == true)
{
    // Open document
    string filename = dlg.FileName;
}

編輯:問題已解決(以下解決方案)

該錯誤來自表單設計器。 最初,我在表單中刪除了FolderBrowserDialog對象。 默認情況下,Visual Studio 2015創建一個RootFolder設置為Desktop的對象。 現在,即使將SelectedPath設置為目標文件夾,FolderBrowserDialog仍將代替它打開桌面文件夾。

因此,我在事件處理程序中實例化了FolderBrowserDialog對象,並將SelectedPath設置為目標文件夾,而未設置RootFolder。 現在它就像一種魅力。

private void B_Browse_Click(object sender, EventArgs e)
{
        FolderBrowserDialog fbd = new FolderBrowserDialog();
        fbd.SelectedPath = MyTargetFolder;
        DialogResult result = fbd.ShowDialog();
        // do stuff
}    

謝謝大家,祝你有美好的一天:)

對於WinForms,您應該使用System.Windows.Forms.OpenFileDialog對象。

您可以使用FolderBrowseDialog設置開始文件夾,問題是樹形視圖不會滾動到該文件夾​​,請參見參考的SO問題。

為什么FolderBrowserDialog對話框無法滾動到所選文件夾?

        FolderBrowserDialog fbd = new FolderBrowserDialog();
        fbd.RootFolder = Environment.SpecialFolder.MyComputer;
        fbd.SelectedPath = @"C:\SomeFolder\";
        fbd.ShowDialog();

確保using System.Windows.Forms語句。

然后,這真的很容易:

OpenFileDialog dlg = new OpenFileDialog();
dlg.FileName = "Document";
dlg.DefaultExt = ".txt";
dlg.Filter = "Text documents (.txt)|*.txt";


Nullable<bool> result = dlg.ShowDialog(); 
// I get an error on this "cannot implicitly convert"
DialogResult result = dlg.ShowDialog();


if (result == true) //doesn't work with DialogResult
{
string filename = dlg.FileName;
}

老實說,這有很多問題。 看到這是另一篇有關堆棧的文章。 希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM