如何使用asp.net从远程服务器下载文件

时间:2022-04-09 15:19:20

The below code works fine for downloading a file from a current pc.plz suggest me how to download it from remote server using ip address or any method

下面的代码适用于从当前pc上下载文件。plz建议我如何使用ip地址或任何方法从远程服务器下载它。

protected void Button1_Click(object sender, EventArgs e)
{
    const string fName = @"C:\ITFSPDFbills\February\AA.pdf";
    FileInfo fi = new FileInfo(fName);
    long sz = fi.Length;

    Response.ClearContent();
    Response.ContentType = MimeType(Path.GetExtension(fName));
    Response.AddHeader("Content-Disposition", string.Format("attachment; filename = {0}", System.IO.Path.GetFileName(fName)));
    Response.AddHeader("Content-Length", sz.ToString("F0"));
    Response.TransmitFile(fName);
    Response.End();
}

public static string MimeType(string Extension)
{
    string mime = "application/octetstream";
    if (string.IsNullOrEmpty(Extension))
        return mime;

    string ext = Extension.ToLower();
    Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
    if (rk != null && rk.GetValue("Content Type") != null)
        mime = rk.GetValue("Content Type").ToString();
    return mime;
}

2 个解决方案

#1


3  

It would be easier to do it like this:

这样做会更容易:

WebClient webClient = new WebClient();
webClient.DownloadFile(remoteFileUrl, localFileName);

#2


-1  

You can use HttpWebRequest, like this:

您可以使用HttpWebRequest,如下所示:

        Uri uri = new Uri(""); // Here goes uri to the file.
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);

        using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
        {
            using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
            {
                // Process response.
            }
        }

#1


3  

It would be easier to do it like this:

这样做会更容易:

WebClient webClient = new WebClient();
webClient.DownloadFile(remoteFileUrl, localFileName);

#2


-1  

You can use HttpWebRequest, like this:

您可以使用HttpWebRequest,如下所示:

        Uri uri = new Uri(""); // Here goes uri to the file.
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);

        using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
        {
            using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
            {
                // Process response.
            }
        }