2011-07-25 19 views
3

我正在使用ExtractAssociatedIcon方法檢索文件的圖標。我的希望是檢索用戶在瀏覽器窗口中看到的相同圖標。ExtractAssociatedIcon返回null

public static Icon GetIcon(string fileName) 
    { 
     try 
     { 
      Icon icon = Icon.ExtractAssociatedIcon(fileName); 
      return icon; 
     } 
     catch 
     { 
      return null; 
     } 
    } 

這項工作99%的時間。但是,如果用戶已鏈接到共享路徑上的文件(如\\SOME_SERVER\my documents\this file.pdf),則它將返回空值。它通過「catch」來解釋,文件路徑不是有效的路徑。

它是一個有效的URI(我已驗證文件是否存在,是否可讀等),但不是使用X:\ some \ Folder表示法的有效完全限定驅動器路徑。

如果可以,我該如何解決這個問題?

謝謝。

重新更新

這是我結束了與解決方案。它比第一次更新更清潔。非常感謝Chris Haas,他的回答是評論,而不是直接回答。如果/當他把它作爲一個直接的答案,我會更新這個。

我仍然不得不下降到一個較低的水平,並通過C++庫取圖標,但我所需要的唯一的庫列表如下:

#region Old-School method 
    [DllImport("shell32.dll")] 
    static extern IntPtr ExtractAssociatedIcon(IntPtr hInst, 
     StringBuilder lpIconPath, out ushort lpiIcon); 

    public static Icon GetIconOldSchool(string fileName) 
    { 
     ushort uicon; 
     StringBuilder strB = new StringBuilder(fileName); 
     IntPtr handle = ExtractAssociatedIcon(IntPtr.Zero, strB, out uicon); 
     Icon ico = Icon.FromHandle(handle); 

     return ico; 
    } 
    #endregion 

一次,我所定義的上述方法中,GetIcon()方法變爲:

public static Icon GetIcon(string fileName) 
    { 
     try 
     { 
      Icon icon = Icon.ExtractAssociatedIcon(fileName); 
      return icon; 
     } 
     catch 
     { 
      try 
      { 
       Icon icon2 = GetIconOldSchool(fileName); 
       return icon2; 
      } 
      catch 
      { 
       return null; 
      } 
     } 
    } 
+1

可能重複[如何從網絡共享文件關聯的圖標(http://stackoverflow.com/questions/1842226/how從網絡共享文件中獲取相關圖標 –

+1

ExtractAssociatedIcon的MSDN文檔說,如果FilePath指示通用命名約定(UNC)路徑,將會拋出ArgumentException異常。http://msdn.microsoft.com/en-us/library/system.drawing.icon.extractassociatedicon.aspx –

+0

是的。但是,這對我如何獲得圖標沒有幫助。 =)這方面的任何建議? – Jerry

回答

2

(評論變成後 - CTIP)

退房的link here最終導致P/Invoke.net用下面的代碼:

[DllImport("shell32.dll")] 
static extern IntPtr ExtractAssociatedIcon(IntPtr hInst, StringBuilder lpIconPath, out ushort lpiIcon); 

[DllImport("shell32.dll")] 
static extern IntPtr ExtractIcon(IntPtr hInst, string lpszExeFileName, int nIconIndex); 

_

ushort uicon; 
StringBuilder strB = new StringBuilder(YOUR_FILE_PATH); 
IntPtr handle = ExtractAssociatedIcon(this.Handle, strB, out uicon); 
Icon ico = Icon.FromHandle(handle); 

return ico.ToBitmap();