2013-11-22 78 views
0

我试图从限制访问并将其返回给我的wpf应用程序中的某个位置的位置读取图像。问题是,我似乎无法避开这个错误: A first chance exception of type 'System.Runtime.InteropServices.COMException' occurred in PresentationCore.dll Additional information: Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))使用模拟图像读取图像

下面的代码:

public BitmapImage GetImage() 
{ 
    var bitmap = new BitmapImage(); 
    var impersonation = new ImpersonationManager(Resources.Username, 
       Resources.Domain, 
       Resources.Password); 
    using (impersonation.SafeTokenHandle) 
    { 
     using (var newId = new WindowsIdentity(impersonation.SafeTokenHandle.DangerousGetHandle())) 
     { 
      using (newId.Impersonate()) 
      { 
       bitmap.BeginInit(); 
       bitmap.UriSource = new Uri(@"\\restrictedpath\\to\\image.jpg", UriKind.Absolute); 
       bitmap.EndInit(); 
      } 
     } 
    } 
    return bitmap; 
} 

我下运行这个程序并没有获得restrictedpath Windows用户,但vim的信任状我用于模仿是好事,否则模仿很好。 ImpersonationManager只是一个包装。

这可能吗?

+0

URI不会那样工作。它需要有一个像C:\\ restrictedpath \\到\\ image.jpg“',或者更好的'@”C:\ restrictedpath \到\ image.jpg“'的驱动器盘符。但这并不能解释这个例外。 – Clemens

+0

@Clemens嗯,不是真的UNC路径工作得很好......否则你将如何访问未映射的共享驱动器?而且这个代码很好的减去了异常。如果我有权访问该驱动器,那么一切都很好。完全同意'@'我从实际代码中修补了这个例子,并错过了这个例子。 – Nicros

+0

如果这是一个UNC路径,你应该写'@“\\ restrictedpath \ to \ image.jpg”',其中'restrictedpath'是服务器名称,对不对? – Clemens

回答

0

所以如果有人遇到这个问题,我的确弄明白了。我不得不打开一个流读取该文件,然后分配给位图的流来源:

public BitmapImage GetImage() 
{ 
    var bitmap = new BitmapImage(); 

    var impersonation = new ImpersonationManager(Resources.Username, 
       Resources.Domain, 
       Resources.Password); 
    using (impersonation.SafeTokenHandle) 
    using (var newId = new WindowsIdentity(impersonation.SafeTokenHandle.DangerousGetHandle())) 
    using (newId.Impersonate()) 
    { 
     using (Stream stream = File.OpenRead(@"\\restrictedpath\\to\\image.jpg")) 
     { 
      bitmap.BeginInit(); 
      stream.Flush(); 
      stream.Position = 0; 
      bitmap.StreamSource = stream; 
      bitmap.CacheOption = BitmapCacheOption.OnLoad; 
      bitmap.EndInit(); 
      bitmap.Freeze(); 
     } 
    } 

    return bitmap; 
} 

这和bitmap.Freeze()了我的问题照顾。