'How to download file as browser in c#

This is the scenario:

I am trying to download a file from a page, I am getting the URL's from a HTML table which I extract the inner text that contains the URL.

Every URL downloads a file that can be an excel file, word file, even a pdf file. If I do a copy/paste to the browser, the file is downloaded as I expect but if I try to download from code, the files are downloaded empty.

The WebRequest try:

        string DocumentUrl = @"http://irc.infusa.com/Windchill/servlet/AttachmentsDownloadDirectionServlet?oid=OR:wt.doc.WTDocument:000000001&oid=OR:wt.content.ApplicationData:000000001&role=PRIMARY ";
       
        string filePath = @"C:\Developer\Doc\" + DocumentId + ".docx";

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(DocumentUrl);
        request.Credentials = new NetworkCredential(Credencial.FWDUser, Credencial.DecryptedPassword);


        if (File.Exists(filePath)) File.Delete(filePath);
        try
        {
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())

            using (Stream stream = response.GetResponseStream())
            using (FileStream os = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write))
            {
                byte[] buff = new byte[102400];
                int c = 0;
                while ((c = stream.Read(buff, 0, 10400)) > 0)
                {
                    os.Write(buff, 0, c);
                    os.Flush();
                }
                os.Close();
                stream.Close(); ;
            }
        }
        catch (Exception ex)
        {

            Console.WriteLine(ex.StackTrace);

        }

The HttpClient Try:

   var httpClient = new HttpClient();
        using (var stream = await httpClient.GetStreamAsync(DocumentUrl))
        {
            using (var fileStream = new FileStream("cc.docx", FileMode.CreateNew))
            {
                await stream.CopyToAsync(fileStream);
            }
        }

The webclient try:

   using (WebClient webClient = new WebClient())
        { 
            webClient.Credentials = new NetworkCredential(Credencial.User, Credencial.DecryptedPassword);
            webClient.DownloadFile(new Uri(DocumentUrl), filePath);
        }

I do not know what type of file is gonna be downloaded so I try the three extensions.

Well at this point, I tried to download using webclient, HTTP client and WebRequest and the files are downloaded every time empty.

I would like to just call the URL and save the files to a directory, is that possible?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source