forked from NewLifeX/X
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIOHelper.cs
62 lines (54 loc) · 2.01 KB
/
IOHelper.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Text;
namespace NewLife.IP
{
static class IOHelper
{
#region 压缩/解压缩 数据
/// <summary>解压缩数据流</summary>
/// <param name="inStream">输入流</param>
/// <param name="outStream">输出流</param>
public static void Decompress(Stream inStream, Stream outStream)
{
// 第三个参数为true,保持数据流打开,内部不应该干涉外部,不要关闭外部的数据流
using (var stream = new GZipStream(inStream, CompressionMode.Decompress, true))
{
CopyTo(stream, outStream);
stream.Close();
}
}
#endregion
#region 复制数据流
/// <summary>复制数据流</summary>
/// <param name="src">源数据流</param>
/// <param name="des">目的数据流</param>
/// <param name="bufferSize">缓冲区大小,也就是每次复制的大小</param>
/// <param name="max">最大复制字节数</param>
/// <returns>返回复制的总字节数</returns>
public static Int32 CopyTo(Stream src, Stream des, Int32 bufferSize = 0, Int32 max = 0)
{
if (bufferSize <= 0) bufferSize = 1024;
var buffer = new Byte[bufferSize];
Int32 total = 0;
while (true)
{
var count = bufferSize;
if (max > 0)
{
if (total >= max) break;
// 最后一次读取大小不同
if (count > max - total) count = max - total;
}
count = src.Read(buffer, 0, count);
if (count <= 0) break;
total += count;
des.Write(buffer, 0, count);
}
return total;
}
#endregion
}
}