c# - 从 url 下载 .xls 文件

标签 c# excel httpwebrequest httpwebresponse

我正在尝试从 url 下载 xls 文件: http://www.site.com/ff/excel/file.aspx?deven=0

我正在使用此代码,但下载完成后文件未正确下载。如何正确下载此文件?

string remoteFilename="http://www.site.com/ff/excel/file.aspx?deven=0";
string localFilename = "D:\\1\\1.xls";
Stream remoteStream = null;
Stream localStream = null;
WebResponse response = null;

try
{
    // Create a request for the specified remote file name
    WebRequest request = WebRequest.Create(remoteFilename);
    if (request != null)
    {
        // Send the request to the server and retrieve the
        // WebResponse object 
        response = request.GetResponse();
        response.ContentType = "application/vnd.ms-excel";

        if (response != null)
        {
            // Once the WebResponse object has been retrieved,
            // get the stream object associated with the response's data
            remoteStream = response.GetResponseStream();

            // Create the local file
            localStream = File.Create(localFilename);

            // Allocate a 1k buffer
            byte[] buffer = new byte[1024];
            int bytesRead;

            // Simple do/while loop to read from stream until
            // no bytes are returned
            do
            {
                // Read data (up to 1k) from the stream
                bytesRead = remoteStream.Read(buffer, 0, buffer.Length);

                // Write the data to the local file
                localStream.Write(buffer, 0, bytesRead);

                // Increment total bytes processed

            } while (bytesRead > 0);
        }
    }
}
catch (Exception e)
{
    MessageBox.Show(e.Message);
}
finally
{
    // Close the response and streams objects here 
    // to make sure they're closed even if an exception
    // is thrown at some point
    if (response != null) response.Close();
    if (remoteStream != null) remoteStream.Close();
    if (localStream != null) localStream.Close();
}
MessageBox.Show("file downl");

最佳答案

使用WebClient ,就简单多了:

using (WebClient webClient = new WebClient())
{
    webClient.DownloadFile(remoteFileName, localFilename);
}

if(File.Exists(localFilename))
    MessageBox.Show("File Downloaded");

关于c# - 从 url 下载 .xls 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21790758/

相关文章:

c# - 从 Azure Blob 存储反序列化对象的最快方法?

c# - 使用文本框更改控件

java - Jackcess:MSAccess 数据库的字符集错误

c# - HttpWebRequest 和 Uri 改变 requestUri

c# - 如何在 http header 中设置用户代理

c# - 根据参数类型调用函数

c# - 如何使聚合根方法仅可用于领域事件,而无其他。

通过使用用户输入框移动/上移一系列单元格来覆盖单元格的 VBA 代码

Excel VBA - 检查工作表是否受密码保护

c# - 如何解决 "The operation has timed out"错误