c#下载奇怪的行为

时间:2014-07-15 21:40:43

标签: c# httpwebrequest webrequest tableau

所以我尝试使用C#从互联网下载文件,有两种文件:.twb.twbx,其中.twbx是zip包含.twb和另外两个文件夹。我的下载程序在下载.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;
    }

1 个答案:

答案 0 :(得分:1)

您不应该将二进制内容解码为文本,因为这会破坏二进制文件。只需将输入流中的原始字节复制到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();