说起下载文件,大家都会想起http和FTP下载。http和ftp,其实底层都是基于socket通信,只不过http和ftp协议格式定义不一样而已。
下载文件,要看服务器支持什么类型的协议,如果只支持http,那你就用httpwebrequest类好了,如果支持FTP,那你就用FTP的类来下载文件。
下面是我对两者的总结使用。
http:
/// <summary>下载安装包</summary> public void downloadPack(string macCode ,string appType,string address) { StringBuilder data = new StringBuilder(); data.Append("{\"cpu\":\"" + macCode + "\""); data.Append(",\"appType\":\"" + appType + "\"}"); //data.Append(",\"softwareVersion\":\"" + iniFile.IniReadValue("USER", "versionNo") + "\""); ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address); request.Headers.Add("X-Auth-Token", HttpUtility.UrlEncode("openstack")); request.Method = "POST"; request.ContentType = "application/json"; request.Accept = "application/json"; byte[] byteData = Encoding.UTF8.GetBytes(data.ToString()); //把要下载的http的文件的相关信息告诉后台 using (Stream postStream = request.GetRequestStream()) { postStream.Write(byteData, 0, byteData.Length); } Log.AddLog("Download", "2"); sc.start(); process = 0; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { Log.AddLog("Download", "3"); int all_count = 0; using (Stream reader = response.GetResponseStream()) { Log.AddLog("Download", filePath); using (FileStream fw = new FileStream(filePath, FileMode.Create, FileAccess.Write)) { Log.AddLog("Download", "5"); byte[] buffer = new byte[1024 * 10]; while (true) { Log.AddLog("Download", all_count.ToString()); int count = reader.Read(buffer, 0, buffer.Length); all_count += count; fw.Write(buffer, 0, count); sc.setSize(all_count); writeCount += (ulong)count; process = (float)writeCount / (float)fileSize; if (count <= 0) { break; } } isFinish = true; sc.stop(); } } } }