2015-10-23 90 views
4

我想在Xamarin Forms Cross Platform中創建一個zip文件。 我爲每個平臺,iOS和Android使用自定義的方式。 在iOS中使用庫ZipArchive,但我沒有找到Android的替代方案。在Xamarin Forms中創建Zip文件Android

所以我嘗試做它本地(創建只有一個文件的zip),但zip文件被創建爲空。

public void Compress(string path, string filename, string zipname) 
{ 
    var personalpath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); 
    string folder = Path.Combine(personalpath, path); 
    string zippath = Path.Combine(folder, zipname); 
    string filepath = Path.Combine(folder, filename); 

    System.IO.FileStream fos = new System.IO.FileStream(zippath, FileMode.OpenOrCreate); 
    Java.Util.Zip.ZipOutputStream zos = new Java.Util.Zip.ZipOutputStream(fos); 

    ZipEntry entry = new ZipEntry(filename.Substring(filename.LastIndexOf("/") + 1)); 
    byte[] fileContents = File.ReadAllBytes(filepath); 
    zos.Write(fileContents); 
    zos.CloseEntry(); 
} 
+2

應該丟棄fos和zos。不知道這是否能解決你的問題。 –

+0

你是對的!需要關閉ZOS並部署FOS – jpintor

+0

我已將您的評論和解決方案移至社區wiki。 –

回答

1

解決方案由Leo Nix和OP。

需要關閉ZOS。
應該丟棄fos和zos。

... 
    zos.CloseEntry(); 
    zos.Close(); 

    zos.Dispose(); 
    fos.Dispose(); 
} 
1

我注意到問題和解決方案代碼並不完整。我不得不改變一些東西,使其工作,所以這裏是完整的代碼:

public void ZipFile(string fullZipFileName, params string[] fullFileName) 
{ 
    using (FileStream fs = new FileStream(fullZipFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite)) 
    { 
     using (ZipOutputStream zs = new ZipOutputStream(fs)) 
     { 
      foreach (var file in fullFileName) 
      { 
       string fileName = Path.GetFileName(file); 

       ZipEntry zipEntry = new ZipEntry(fileName); 
       zs.PutNextEntry(zipEntry); 
       byte[] fileContent = System.IO.File.ReadAllBytes(file); 
       zs.Write(fileContent); 
       zs.CloseEntry(); 
      } 

      zs.Close(); 
     } 
     fs.Close(); 
    } 
} 

我希望它有幫助。