在拔掉System.IO.IOException后,Xamarin Android从SD卡解压缩文件

时间:2017-05-16 12:09:28

标签: c# android xamarin android-sdcard ioexception

我想将SD卡中的zip文件解压缩到/ internal_Storage。它没有问题,工作顺利完成。 当我突然拔掉插卡时出现问题,然后我遇到了这个例外:

未处理的例外:

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卡时,应用程序都会崩溃。谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

当使用块退出时,它会调用实例上的Dispose()来控制'。你的using块是在zipInputStream周围,所以当使用块关闭时,将调用zipInputStream上的Dispose()方法。可能是从zipInputStream的Dispose方法中抛出此异常。在using块周围添加一个try块来测试这个假设。