2012-04-02 21 views
0

我對這種方法有點麻煩。combolistbox.Item.Add(FileInfo)不一致?

當我通過dragDropFiles中的FileInfo類型對象循環並將每個對象單獨添加到CLB時,我會檢查該項目時獲取FullName屬性(文件的完整路徑,這是我需要的)。 但是,使用hotFolderFiles而不是路徑,它只給出了文件名。

我不明白這一點,因爲他們以相同的方式添加相同的對象類型。

(我也試過讓FileInfo的使用DirectoryInfo的,而不是我的字典用同樣的結果熱文件夾中的文件)

爲什麼這種行爲不一致? (我怎樣才能得到它返回的fileInfo全名,而不是名稱?)

public frmFilesFound(string hotFolderPath, Dictionary<string, FileInfo> dragDropFiles, Dictionary<string, FileInfo> hotFolderFiles, bool ReadOnly) 
    { 
     try 
     { 
      InitializeComponent(); 
      readOnly = ReadOnly; 

      btnSelectAll.Visible = true; 
      clbSelectFilesFound.Visible = true; 
      clbSelectFilesFound.FormattingEnabled = true; 
      clbSelectFilesFound.Format += (s, e) => { e.Value = string.Format("{0}", ((FileInfo)e.ListItem).Name); }; 


      foreach (FileInfo fileInfo in dragDropFiles.Values) 
      { 
       if (!clbSelectFilesFound.Items.Contains(fileInfo)) 
       { 
        try 
        { 
         // If file not already present, add it to listbox 
         clbSelectFilesFound.Items.Add(fileInfo); 
        } 
        catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } 
       } 
      } 
      //intended to be hot folder path 
      if (!String.IsNullOrEmpty(hotFolderPath)) 
      { 
       DirectoryInfo dirInfo = new DirectoryInfo(hotFolderPath); 

       foreach (FileInfo fileInfo in dirInfo.GetFiles()) 
       //foreach (FileInfo fileInfo in hotFolderFiles.Values) 
       { 
        if (!clbSelectFilesFound.Items.Contains(fileInfo)) 
        { 
          try 
          { 
           clbSelectFilesFound.Items.Add(fileInfo); 
          } 
          catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } 
        } 
       } 
      } 
      lblDisplayedSelectMessage.Text = "More than one file is waiting. Please select the files you would like to use."; 
     } 
     catch (Exception ex) 
     { MessageBox.Show(ex.ToString()); } 

    } 

回答

0

你爲什麼不只是總是添加(fileInfo.FullName)?

+1

這是一個組合框的只是美女,你可以將對象添加到它。否則,f.e.屬性SelectedItem將沒有用處。 – 2012-04-02 12:52:20

+0

然後將其數據成員過濾器設置爲「FullName」,或者使用fileInfo自身標記該項目,以備將來參考。 – SimpleVar 2012-04-02 12:54:35

+0

我正在添加對象,因爲我想在comboListBox中顯示文件名,但是我想從選擇結果中使用FullName。 – negligible 2012-04-02 13:10:34

1

這是因爲DirectoryInfo.GetFiles方法只填充文件的名稱,而不是完整的路徑。

試試這個格式,如果你只是想在所有的情況下顯示文件名:

clbSelectFilesFound.Format += (s, e) => { e.Value = Path.GetFileNameWithoutExtension(((FileInfo)e.ListItem).Name); };

+0

當我使用我的字典時,我得到相同的結果,請參閱下面的註釋行,而不是'GetFiles()'。 但是,字典方式在第一個ForEach循環內正常工作。 我的格式正在按預期工作。 – negligible 2012-04-02 13:16:23

+0

是的,但我們沒有看到dragDropFiles和hotFolderFiles來自哪裏。所以我只能建議這個解決方法 – 2012-04-02 13:17:50

+0

我不明白你爲什麼認爲這將是一個解決辦法,這與我現有的格式化程序具有完全相同的影響。 (和我的問題不是格式) 你可以看到dragDropFiles和hotFolderFiles來自構造函數... – negligible 2012-04-02 13:27:21