我有以下代码用于添加到 Zip 中/从 Zip 中提取。我正在尝试重构它以使其可以测试。有人可以提供有关我如何做到这一点的指示吗?另外:我使用 Moq 作为我的模拟框架和 MSTest 作为我的单元测试工具
private const long BufferSize = 4096;
public static void ExtractZip(string zipFilename, string folder) {
using (var zip = System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate)) {
foreach (var part in zip.GetParts()) {
using (var reader = new StreamReader(part.GetStream(FileMode.Open, FileAccess.Read))) {
using (var writer = new FileStream(folder + "\\" + Path.GetFileName(part.Uri.OriginalString),
FileMode.Create, FileAccess.Write)) {
var buffer = System.Text.Encoding.UTF8.GetBytes(reader.ReadToEnd());
writer.Write(buffer, 0, buffer.Length);
}
}
}
}
}
public static void AddFileToZip(string zipFilename, string fileToAdd) {
using (var zip = System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate)) {
var destFilename = ".\\" + Path.GetFileName(fileToAdd);
var uri = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative));
if (zip.PartExists(uri)) {
zip.DeletePart(uri);
}
var part = zip.CreatePart(uri, "", CompressionOption.Normal);
using (var fileStream = new FileStream(fileToAdd, FileMode.Open, FileAccess.Read)) {
using (var dest = part.GetStream()) {
CopyStream(fileStream, dest);
}
}
}
}
提前致谢。