2013-03-27 121 views
-1

通過下面的方式,我可以閱讀。如何在C#中讀取圖像尺寸wpf - 沒有BitmapImage的配置方法

但沒有任何處理方法,所以我以後不能刪除文件。

所以下面的方法失敗了。

我無法想出一個適當的解決方案。

在C#4.5 WPF應用程序中無法識別位圖類。

謝謝

DirectoryInfo dInfo = new DirectoryInfo(@"C:\pokemon_files\images\"); 
    FileInfo[] subFiles = dInfo.GetFiles(); 

    BitmapImage myImg; 
    foreach (var vrImage in subFiles) 
    { 
     string srFilePath = vrImage.FullName; 
     System.Uri myUri = new Uri(srFilePath); 
     myImg = new BitmapImage(myUri); 

     if (myImg.Width < 50) 
     { 
      File.Delete(srFilePath); 
      continue; 
     } 
    } 
+0

你的錯誤是什麼? – 2013-03-27 11:18:04

+0

你會得到哪個錯誤信息? – roqz 2013-03-27 11:20:00

+0

重複http://stackoverflow.com/questions/10319447/release-handle-on-file-imagesource-from-bitmapimage – 2013-03-27 11:25:29

回答

1

我假設你的錯誤是試圖刪除這是目前在用位圖(我不記得異常名)使用 的文件引起的。

有一個解決方案,即:製作一個字節流。

byte[] imageData; 

using(var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) 
using(var binaryReader = new BinaryReader(fileStream)) 
{ 
    imageData = binaryReader.ReadBytes((int)fileStream.Length); 
} 

var bitmap = new BitmapImage(); 
bitmap.BeginInit(); 
bitmap.StreamSource = new MemoryStream(imageData); 
bitmap.EndInit(); 

//Now you can check the width & height, the file stream should be closed so you can 
//delete the file. 

[編輯] 如果你不想通過BinaryReader讀取的字節數,總有this solution如果你想從文件讀取的所有字節。

+0

你應該總是檢查你從'ReadBytes'方法收到的字節量。 – 2013-03-27 11:28:21