11
/// <summary>
/// 文件上传
/// </summary>
/// <param name="filePath">原路径(绝对路径)包括文件名</param>
/// <param name="objPath">目标文件夹:服务器下的相对路径 不填为根目录</param>
public static bool FileUpLoad(string filePath, string objPath = "")
{
bool isOk = false;
string url = path;
if (objPath != "")
url += objPath + "/";
FtpWebRequest reqFTP = null;
ProgressBarForm progressBarForm = null;
try
{
FileInfo fileInfo = new FileInfo(filePath);
reqFTP = getFtpWebRequest(url, fileInfo.Name);
progressBarForm = new ProgressBarForm();
progressBarForm.Show();
using (FileStream fs = fileInfo.OpenRead())
using (Stream stream = reqFTP.GetRequestStream())
{
int buff = 1024 * 1024;
byte[] b = new byte[buff];
int count = 1;
double total = Math.Ceiling(fs.Length / (float)buff);
int len;
while ((len = fs.Read(b, 0, b.Length)) > 0)
{
stream.Write(b, 0, len);
progressBarForm.LoadProgressBarRate(count++, (float)total);
}
}
isOk = true;
}
catch (Exception ex)
{
Logger.Error(ex);
}
finally
{
if (progressBarForm != null)
progressBarForm.Close();
}
return isOk;
}
private static FtpWebRequest getFtpWebRequest(string url, string fileInfoName)
{
string requestUri = url + fileInfoName;
FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(requestUri));
reqFTP.Credentials = new NetworkCredential(username, password); //设置连接到FTP的帐号密码
reqFTP.KeepAlive = false; //设置请求完成后是否保持连接
reqFTP.Method = WebRequestMethods.Ftp.UploadFile; //指定执行命令
reqFTP.UseBinary = true; //指定数据传输类型
return reqFTP;
}
public void Download(string remoteFile, string localFile)
{
ProgressBarForm progressBarForm = null;
try
{
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(path + "/" + remoteFile);
ftpRequest.Credentials = new NetworkCredential(username, password);
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
ftpStream = ftpResponse.GetResponseStream();
long serverFileSize = GetFileSize(remoteFile);
FileStream localFileStream = new FileStream(localFile, FileMode.Create);
byte[] byteBuffer = new byte[bufferSize];
progressBarForm = new ProgressBarForm();
progressBarForm.Show();
int len;
while ((len = ftpStream.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
{
localFileStream.Write(byteBuffer, 0, len);
var current = (localFileStream.Length * 1.0d / serverFileSize) * 100;
progressBarForm.LoadProgressBarRate((int)current, 100);
}
localFileStream.Close();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;
}
catch (Exception ex)
{
Logger.Error(ex);
Console.WriteLine(ex.ToString());
}
finally
{
if (progressBarForm != null)
progressBarForm.Close();
}
}