c#下载怪异行为
本文关键字:下载 | 更新日期: 2023-09-27 18:13:10
所以我试图使用C#
从互联网下载文件,有两种文件:.twb
和.twbx
,其中.twbx
是包含.twb
和其他两个文件夹的zip。我的下载程序在下载.twb
文件时工作得很好,但是当我下载.twbx
文件时,我总是以一个完全不同的文件结束-相同的名称,但大小和内容非常不同。知道为什么会这样吗?
下面是下载代码:
request = setUpRequest(dLink);
((HttpWebRequest)request).KeepAlive = true;
((HttpWebRequest)request).Host = host;
((HttpWebRequest)request).Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
((HttpWebRequest)request).Referer = referer;
((HttpWebRequest)request).Headers["Accept-Encoding"] = "gzip,deflate,sdch";
((HttpWebRequest)request).Headers["X-CSRF-Token"] = CSRF_TOKEN;
((HttpWebRequest)request).Headers["X-Prototype-Version"] = "1.7_rc3";
((HttpWebRequest)request).Headers["X-Requested-With"] = "XMLHttpRequest";
((HttpWebRequest)request).Headers["Origin"] = origin;
response = getResponse(request);
Stream resp = response.GetResponseStream();
if ((response.ContentEncoding.ToLower().Contains("gzip")))
{
resp = new System.IO.Compression.GZipStream(resp, System.IO.Compression.CompressionMode.Decompress);
}
else if ((response.ContentEncoding.ToLower().Contains("deflate")))
{
resp = new System.IO.Compression.DeflateStream(resp, System.IO.Compression.CompressionMode.Decompress);
}
String buffer = new StreamReader(resp, System.Text.Encoding.UTF8).ReadToEnd();
String filename = response.Headers["Content-Disposition"];
filename = Regex.Match(filename, "'".*'"").Value;
filename = filename.Substring(1, filename.Length - 2);
//Console.WriteLine("Writing content to {0}...", filename);
System.IO.File.WriteAllText(directory + filename, buffer);
resp.Close();
resp.Dispose();
,这里是setUpRequest()
,如果你好奇的话:
private static WebRequest setUpRequest(String url)
{
WebRequest request = WebRequest.Create(url);
((HttpWebRequest)request).CookieContainer = cookieContainer;
request.PreAuthenticate = true;
request.UseDefaultCredentials = true;
((HttpWebRequest)request).AllowAutoRedirect = false;
return request;
}
您不应该将二进制内容解码为文本,因为这会破坏二进制内容。只需将原始字节从输入流复制到FileStream
:
String filename = response.Headers["Content-Disposition"];
filename = Regex.Match(filename, "'".*'"").Value;
filename = filename.Substring(1, filename.Length - 2);
using (FileStream target = new FileStream(directory + filename, FileMode.Create, FileAccess.Write))
resp.CopyTo(target);
resp.Close();
resp.Dispose();