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();
}
嘗試使用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