您的位置:首页 > 产品设计 > UI/UE

C#中实现zip协议,通过WebRequest查询zip文件内容。统一访问接口

2011-05-14 19:40 976 查看
private static void Test() {
bool httpResult = WebRequest.RegisterPrefix("zip://C", new ZipWebRequestCreator(@"C:/"));
WebRequest req = WebRequest.Create(@"zip://C/output.zip/index.html");
WebResponse response = req.GetResponse();
using (Stream stream = response.GetResponseStream()) {
System.Console.WriteLine(stream.Length);

using (Stream mem = new FileStream(@"C:/1.txt", FileMode.Create)) {
int size = 0;
while (true) {
byte[] buffer = new byte[4096];
size = stream.Read(buffer, 0, buffer.Length);

if (size > 0) {
mem.Write(buffer, 0, size);
} else {
break;
}
}
}
}
}

public class ZipWebRequestCreator : IWebRequestCreate {
public WebRequest Create(Uri uri) {
return new ZipWebRequest(uri, _zipDir);
}
private string _zipDir;
public ZipWebRequestCreator(string zipDir) {
_zipDir = zipDir;
if (string.IsNullOrEmpty(zipDir)) {
_zipDir = Path.GetDirectoryName(this.GetType().Assembly.Location);
}
}
}

public class ZipWebResponse : WebResponse {
public override String ContentType {
get { return ""; }
set { /* override */ }
}
public override Stream GetResponseStream() {
string zipFileName = Path.Combine(_zipDir, _zipFile);
if (File.Exists(zipFileName)) {
ZipFile file = new ZipFile(zipFileName);
int index = file.FindEntry(_entryName, true);
if (index == -1) {
throw new FileNotFoundException(_entryName);
}

Stream zipStream = file.GetInputStream(index);
return zipStream;
}
throw new FileNotFoundException(zipFileName);
}
private string _zipDir, _zipFile, _entryName;
internal ZipWebResponse(string zipDir, string absPath) {
_zipDir = zipDir;
if (absPath[0] == '/') absPath = absPath.Substring(1);
int index = absPath.IndexOfAny(new char[] { '/', '//' });
_zipFile = absPath.Substring(0, index);
_entryName = absPath.Substring(index + 1);
}
}

[Serializable]
public class ZipWebRequest : WebRequest, ISerializable {

public override WebResponse GetResponse() {
this.m_syncHint = true;
try {
string absPath = m_uri.AbsolutePath;
ZipWebResponse response = new ZipWebResponse(_zipDir, absPath);
return response;
} catch (Exception exception2) {
//if (Logging.On) {
// Logging.Exception(Logging.Web, this, "GetResponse", exception2);
//}
throw;
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐