c# files downloaded with httpwebrequest and cookies get corrupted

风格不统一 提交于 2021-02-11 06:08:35

问题


I am trying to make a program which is able to download files with URI(URL) using httpwebrequest and cookies(for credential information to keep login status).

I can download files with following code but files get corrupted after being downloaded.

when I download xlsx file(on the web page) into text file at local drive, I see some part of numbers and words from an original file in a corrupted file, therefore I assume I have reached to the right file.

however, when I download xlsx file(on the web page) in xlsx file at local drive, it seems like it fails to open saying

excel cannot open the file 'filename.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.

Is there any way I can keep fully original file content after I download?

I attach a part of result content as well.

private void btsDownload_Click(object sender, EventArgs e)
{
  try
  {
    string filepath1 = @"PathAndNameofFile.txt";                     
    string sTmpCookieString = GetGlobalCookies(webBrowser1.Url.AbsoluteUri);            
    HttpWebRequest fstRequest = (HttpWebRequest)WebRequest.Create(sLinkDwPage);
    fstRequest.Method = "GET";                                                          
    fstRequest.CookieContainer = new System.Net.CookieContainer();                      
    fstRequest.CookieContainer.SetCookies(webBrowser1.Document.Url, sTmpCookieString);
    HttpWebResponse fstResponse = (HttpWebResponse)fstRequest.GetResponse();            
    StreamReader sr = new StreamReader(fstResponse.GetResponseStream());                
    string sPageData = sr.ReadToEnd();                                                  
    sr.Close();                                                                         

    string sViewState = ExtractInputHidden(sPageData, "__VIEWSTATE");                   
    string sEventValidation = this.ExtractInputHidden(sPageData, "__EVENTVALIDATION");  

    string sUrl = ssItemLinkDwPage;                                                  
    HttpWebRequest hwrRequest = (HttpWebRequest)WebRequest.Create(sUrl);
    hwrRequest.Method = "POST";                                                         

    string sPostData = "__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=" + sViewState + "&__EVENTVALIDATION=" + sEventValidation + "&Name=test" + "&Button1=Button";


    ASCIIEncoding encoding = new ASCIIEncoding();
    byte[] bByteArray = encoding.GetBytes(sPostData);
    hwrRequest.ContentType = "application/x-www-form-urlencoded";

    Uri convertedURI = new Uri(ssDwPage);
    hwrRequest.CookieContainer = new System.Net.CookieContainer();
    hwrRequest.CookieContainer.SetCookies(convertedURI, sTmpCookieString);

    hwrRequest.ContentLength = bByteArray.Length;
    Stream sDataStream = hwrRequest.GetRequestStream();
    sDataStream.Write(bByteArray, 0, bByteArray.Length);
    sDataStream.Close();
    using (WebResponse response = hwrRequest.GetResponse())
    {
      using (sDataStream = response.GetResponseStream())
      {
        StreamReader reader = new StreamReader(sDataStream);
        {
          string sResponseFromServer = reader.ReadToEnd();
          FileStream fs = File.Open(filepath1, FileMode.OpenOrCreate, FileAccess.Write);

          Byte[] info = encoding.GetBytes(sResponseFromServer);

          fs.Write(info, 0, info.Length);
          fs.Close();

          reader.Close();
          sDataStream.Close();
          response.Close();
        }
      }
    }
  }
  catch
  {
    MessageBox.Show("Error");
  }
}


回答1:


StreamReader is for dealing with text data. Using it corrupts your binary data(excel file).

Write sDataStream directly to file. For ex.

sDataStream.CopyTo(fs)

PS: I prepared a test case (using similar logic) to show how your code doesn't work

var binaryData = new byte[] { 128,255 };
var sr = new StreamReader(new MemoryStream(binaryData));
var str3 = sr.ReadToEnd();
var newData = new ASCIIEncoding().GetBytes(str3); //<-- 63,63

Just compare binaryData with newData



来源:https://stackoverflow.com/questions/50706561/c-sharp-files-downloaded-with-httpwebrequest-and-cookies-get-corrupted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!