简体   繁体   English

通过Asp.net和C#从外部服务器下载文件

[英]Download a File From a External sever through Asp.net & C#

First,I uploaded a file in a external server and got a url from that server.Now i want to download that uploaded file from the external server through that url which i got from that server through asp.net and c#. 首先,我在外部服务器上传了一个文件并从该服务器获取了一个URL。现在我想通过asp.net和c#从该服务器获取的url从外部服务器下载该上传文件。 I wrote ac# code to download that file, but during that process i got an exception "Exception of type 'System.OutOfMemoryException' was thrown". 我写了ac#代码来下载该文件,但在那个过程中我得到了一个异常“抛出了类型'System.OutOfMemoryException'的异常”。 The following is the c# code which i wrote to download: 以下是我写下载的c#代码:

double dlsize=0;
string Url = "http://www.sample.com/download.zip"; \\File Size: 75MB
int lastindex = Url.LastIndexOf("/");
string TempUrlName = Url.Substring(lastindex + 1, Url.Length - (lastindex + 1));

WebRequest oWebRequest = WebRequest.Create(Url);
oWebRequest.Timeout = -1;
WebResponse oWebResponse = oWebRequest.GetResponse();

if (oWebResponse.ContentType != "text/html; charset=UTF-8")
{
    string myFile = oWebResponse.Headers.Get("Content-Length");
    int TempmyFile = Convert.ToInt32(myFile);
    double bytes_total = Convert.ToDouble(TempmyFile);
    dlSize = Convert.ToDouble(bytes_total / (1024 * 1024));

    System.IO.MemoryStream oMemoryStream = new MemoryStream();
    byte[] buffer = new byte[4096];

    using (System.IO.Stream oStream = oWebResponse.GetResponseStream())
    {
        int Count = 0;
        do
        {
            Count = oStream.Read(buffer, 0, buffer.Length);
            oMemoryStream.Write(buffer, 0, Count);
        } while (Count != 0);
    }

    System.IO.FileStream oFileStream = new System.IO.FileStream("C:\Documents and Settings\arun\Desktop\New Folder\download.zip", System.IO.FileMode.Create);
    oMemoryStream.WriteTo(oFileStream);
    oFileStream.Flush();
    oFileStream.Close();
    oMemoryStream.Flush();
    oMemoryStream.Close();
    oWebResponse.Close();
}

It would be easier to do it like this: 这样做会更容易:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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