日期:2014-05-18 浏览次数:21009 次
public bool Upload(FileInfo localFile, string remoteFileName) { try { bool result = false; if (localFile.Exists) { string url = Host.TrimEnd('/') + RemotePath + remoteFileName; FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.UploadFile); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); //上传数据 using (Stream rs = request.GetRequestStream()) using (FileStream fs = localFile.OpenRead()) { byte[] buffer = new byte[4096];//4K int count = fs.Read(buffer, 0, buffer.Length); while (count > 0) { try { rs.Write(buffer, 0, count); count = fs.Read(buffer, 0, buffer.Length); //request.ServicePoint.ConnectionLeaseTimeout = 1000; } catch { request.ClientCertificates.Clear(); response.GetResponseStream().Close(); response.Close(); request.Abort(); fs.Seek(count, SeekOrigin.Begin); // Thread.Sleep(150000); // request.GetRequestStream().Close(); // rs.Close(); GetFileList(); Append(fs, remoteFileName); 如果出现异常就追加文件流 } } fs.Close(); result = true; } return result; } } catch (Exception ex) { throw new Exception(ex.Message); } throw new Exception(string.Format("本地文件不存在,文件路径:{0}", localFile.FullName)); } /// <summary> /// 给FTP服务器上的文件追加内容 /// </summary> /// <param name="stream">数据流(可通过设置偏移来实现从特定位置开始上传)</param> /// <param name="remoteFileName">FTP服务器上的文件</param> /// <returns>返回一个值,指示是否追加成功</returns> public bool Append(Stream stream, string remoteFileName) { bool result = false; int count=0; try { if (stream != null && stream.CanRead) { //建立连接 string url = Host.TrimEnd('/') + RemotePath + remoteFileName; FtpWebRequest request = CreateRequest(url, WebRequestMethods.Ftp.AppendFile); using (Stream rs = request.GetRequestStream()) { //上传数据 byte[] buffer = new byte[4096];//4K count = stream.Read(buffer, 0, buffer.Length); while (count > 0) { rs.Write(buffer, 0, count); count = stream.Read(buffer, 0, buffer.Length); bool zt = false; while (zt == false) { rs.Write(buffer, 0, count); count = stream.Read(buffer, 0, buffer.Length); }