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

时间:2011-02-24 11:57:52

标签: c# asp.net

首先,我在外部服务器上传了一个文件并从该服务器获取了一个网址。现在我想从外部服务器通过asp.net和c#从该服务器下载的网址下载该文件。 我写了一个c#代码来下载该文件,但在那个过程中我得到了一个例外 “抛出类型'System.OutOfMemoryException'的异常”。 以下是我写下载的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();
}

1 个答案:

答案 0 :(得分:2)

这样做会更容易:

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