简体   繁体   中英

download the file from the navigation link from the website by logging in from Console application C#

I would like to download excel file from the website using user name and password. After logging in, there is a link for downloading the excel file. When I clicked it, the Save as message asks me to save in the desired folder. I am using this function and it doesn't work. It just downloads the html page. Any suggestions would be appreciated.

ftpfullpath is the url + file name

if I use the login form url, it shows error.

    public static void DownloadFileFTP()
        {
            //Delete if Data feed file is already existed
            if (File.Exists(GetFileName.source_path))
            {
                File.Delete(GetFileName.source_path);
            }

            //Create a WebClient
            WebClient request = new WebClient();

            //Set up credentials
            request.Credentials = new NetworkCredential(Properties.Resources.UserName, Properties.Resources.Password);

            //Download the data into Byte array
            byte[] fileData = request.DownloadData(Properties.Resources.ftpfullpath);

            //Create a Filestream to write to Byte array
            FileStream sourceFile = File.Create(GetFileName.source_path);

            try
            {
                //Write full byte array to the file
                sourceFile.Write(fileData, 0, fileData.Length);
                Console.WriteLine("Download Complete " + GetFileName.source_path);
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            finally
            {
                if (sourceFile != null)
                {
                sourceFile.Close();
                sourceFile = null;
                }

            }
        }

Your code is ok, you have to debug page you're downloading from. Most likely it makes redirects before going to file. Browser handles that automatically. Use http://www.fiddler2.com/fiddler2/ to see what's happening when you click the link.

Also try to set referrer = download page url.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM