public static string DownLoadFile(string fileURL)
{
StreamReader rdr = null;
FileStream wrtr = null;
string localFileName = string.Empty;
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(fileURL);
req.Method = "GET";
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
long len = resp.ContentLength;
Stream respStream = resp.GetResponseStream();
localFileName = @"\Program Files\" + fileURL.Substring(fileURL.LastIndexOf("/") + 1);
wrtr = new FileStream(localFileName, FileMode.Create);
byte[] inData = new byte[4096];
int bytesRead = respStream.Read(inData, 0, inData.Length);
while (bytesRead > 0)
{
wrtr.Write(inData, 0, bytesRead);
bytesRead = respStream.Read(inData, 0, inData.Length);
}
//判断下在是否成功
System.IO.FileInfo fi = new FileInfo(localFileName);
if (fi.Length != len) localFileName = string.Empty;
fi = null;
}
catch {}
finally
{
if (rdr != null) rdr.Close();
if (wrtr != null) wrtr.Close();
}
return localFileName;
}
//自己封装头部
public string HttpDownload(string url)
{
try
{
url = url.ToLower().Replace("http://", "");
int offset = url.IndexOf("/");
string Host=url.Substring(0,offset);
string file = url.Substring(offset);
IPHostEntry IpHost = Dns.GetHostEntry(Host);
Socket Sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint point = new IPEndPoint(IpHost.AddressList[0], 80);
Sock.Connect(point);
if (Sock.Connected)
{
string strGet = "GET " + file + " HTTP/1.0\r\n" +
"Host:" + Host + "\r\n" +
"Accept:*/*\r\n" +
"User-Agent:GeneralDownloadApplication\r\n" +
"Connection:Keep-Alive\r\n\r\n";
Byte[] cmd = Encoding.Default.GetBytes(strGet.ToCharArray());
Sock.Send(cmd, cmd.Length, SocketFlags.None);
string strInfo = "";
for (int i = 0; i < 1000; i++) //10s
{
if (Sock.Available > 0)
{
Byte[] bytes = new Byte[1024];
int intSize = Sock.Receive(bytes, 1024, 0);
strInfo += Encoding.Default.GetString(bytes, 0, intSize);
if (strInfo.IndexOf("HTTP/1.1 200 OK") == 0)
{
intSize = strInfo.IndexOf("\r\n\r\n");
if (intSize > 0)
{
return strInfo.Substring(intSize + 4);
}
}
}
Thread.Sleep(10);
}
}
}
catch { }
return "";
}