2017-05-16 50 views
0

我想從sd卡解壓zip文件到/ internal_Storage。它工作得很好,沒有問題,成功完成成功。發生 的問題時,我突然拔出存儲卡,然後我得到這個異常:Xamarin Android從SD卡解壓縮文件,拔出System.IO.IOException異常後

未處理的異常:

System.IO.IOException:無效的句柄路徑「/mnt/sdcard/Sounds.zip」

應用程序崩潰後。

string zipFile = @"/mnt/Sounds.zip"; 
string unZipSoundsFolderPath = @"/data/internal_Storage/Sounds/"; 
using (var zipInputStream = new ZipInputStream(System.IO.File.OpenRead(zipFile))) 
{ 

     ZipEntry ze = null; 

     try 
     { 

      while ((ze = zipInputStream.NextEntry) != null) 
      { 

       if (ze.IsDirectory) 
       { 
        if (!Directory.Exists(unZipSoundsFolderPath + ze.Name)) 
        { 
         Directory.CreateDirectory(unZipSoundsFolderPath + ze.Name); 
        } 
        continue; 
       } 


       FileStream fout = new FileStream(unZipSoundsFolderPath + ze.Name, FileMode.Create); 
       BufferedStream bfout = new BufferedStream(fout); 

       try 
       { 

        byte[] buffer = new byte[2048]; 
        int read = 0; 
        while ((read = zipInputStream.Read(buffer)) != -1) //THIS ROW DROPS EXCEPTION 
        { 
         bfout.Write(buffer, 0, read); 
        } 

       } 
       catch (System.IO.IOException exs)//HERE NOT CAUGHT EXCEPTION 
       { 
        break; 
       } 
       catch (Java.IO.IOException jex)//HERE NOT CAUGHT EXCEPTION 
       { 
        break; 
       } 

       zipInputStream.CloseEntry(); 
       bfout.Close(); 
       fout.Close(); 

      } 

     } 
     catch (System.IO.IOException exs) 
     { 
      System.Diagnostics.Debug.WriteLine(exs.Message); 
      importIsSuccessful = false; 
     } 
     catch (Java.IO.IOException) 
     { 
      importIsSuccessful = false; 
     } 
     catch(Exception ex) 
     { 
      importIsSuccessful = false; 
     } 

     zipInputStream.Close(); 

} 

我做了很多事情,但每當SD卡拔出時,應用程序都會粉碎。謝謝你的幫助!

回答

0

當使用塊退出時,它將調用它正在「控制」的實例上的Dispose()。您使用的塊位於zipInputStream的周圍,因此當使用塊關閉時,將調用zipInputStream上的Dispose()方法。這個異常可能是從zipInputStream的Dispose方法中拋出的。在使用塊周圍添加一個try塊來測試這個假設。

+0

謝謝你的回答。我在using語句中使用了try-catch塊,從我的文章中錯過了它。不幸的結果是相同的:System.IO.IOException:路徑「/mnt/sdcard/Sounds.zip」的句柄無效。我留下了使用聲明,保持try-catch,但異常沒有被任何catch語句捕獲。這是關鍵點:'read = zipInputStream.Read(buffer)'。 Zipinputstream失去了壓縮文件的路徑。任何try-catch都無法捕捉到這個異常,這很奇怪。 – user1223445

+0

您需要掌握異常本身,以便您可以檢查其堆棧跟蹤。這將告訴你Exception從哪裏拋出。 –