2011-02-24 108 views
0

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

尝试使用Web客户端(http://msdn.microsoft.com /en-us/library/system.net.webclient%28v=vs.80%29.aspx)而不是HttpWebRequest/HttpWebResponse,因为您会发现它更容易下载。如果你也可以发布堆栈跟踪,你会得到更好的回应 – Kane 2011-02-24 12:02:01

回答

2

它会更容易做到这一点是这样的:

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