以 iOS 9.0 或 macOS 10.11 為目標的 Xamarin 應用程式可以使用 壓縮架構 來壓縮(編碼)和解壓縮(譯碼)數據。 Xamarin.iOS 會遵循串流 API 提供此架構。 壓縮架構可讓開發人員與壓縮和解壓縮的數據互動,就像是一般數據流一樣,而不需要使用回呼或委派。
壓縮架構提供下列演演算法的支援:
- LZ4
- LZ4 Raw
- Lzfse
- Lzma
- Zlib
使用壓縮架構可讓開發人員在沒有任何第三方連結庫或 NuGet 的情況下執行壓縮作業。 這可減少外部相依性,並確保在所有平臺上都支援壓縮作業(只要它們符合最低OS需求)。
一般檔案解壓縮
壓縮架構會使用 Xamarin.iOS 和 Xamarin.Mac 中的串流 API。 此 API 表示若要壓縮數據,開發人員可以使用 .NET 內其他 IO API 中使用的一般模式。 下列範例示範如何使用壓縮架構來解壓縮數據,這類似於 API 中找到的 System.IO.Compression.DeflateStream
API:
// sample zlib data
static byte [] compressed_data = { 0xf3, 0x48, 0xcd, 0xc9, 0xc9, 0xe7, 0x02, 0x00 };
using (var backing = new MemoryStream (compressed_data)) // compress data to read
using (var decompressing = new CompressionStream (backing, CompressionMode.Decompress, CompressionAlgorithm.Zlib)) // create decompression stream with the correct algorithm
using (var reader = new StreamReader (decompressing))
{
// perform the required stream operations
Console.WriteLine (reader.ReadLine ());
}
會CompressionStream
像其他 System.IO.Streams
一樣實作 IDisposable
介面,因此開發人員應該確保不再需要資源后釋放資源。
一般檔案壓縮
壓縮 API 也允許開發人員在相同的 API 之後壓縮數據。 您可以使用列舉值中所述 CompressionAlgorithm
的其中一個演算法來壓縮數據。
// sample method that copies the data from the source stream to the destination stream
static void CopyStream (Stream src, Stream dest)
{
byte[] array = new byte[1024];
int bytes_read;
bytes_read = src.Read (array, 0, 1024);
while (bytes_read != 0) {
dest.Write (array, 0, bytes_read);
bytes_read = src.Read (array, 0, 1024);
}
}
static void CompressExample ()
{
// create some sample data to compress
byte [] data = new byte[100000];
for (int i = 0; i < 100000; i++) {
data[i] = (byte) i;
}
using (var dataStream = new MemoryStream (data)) // stream that contains the data to compress
using (var backing = new MemoryStream ()) // stream in which the compress data will be written
using (var compressing = new CompressionStream (backing, CompressionMode.Compress, CompressionAlgorithm.Zlib, true))
{
// copy the data to the compressing stream
CopyStream (dataStream, compressing);
// at this point, the CompressionStream contains all the data from the dataStream but compressed
// using the zlib algorithm
}
非同步支援
CompressionStream
支援 支援 的所有異步作業System.IO.DeflateStream
,這表示開發人員可以使用 async 關鍵詞來執行壓縮/解壓縮作業,而不會封鎖 UI 線程。