最近在内蒙古出差,做了一个关于ftp上传下载的小程序,在此只是记录一下,也希望各位大牛给出批评和指教!
1. 首先获得FTP的网络允许,即获得连接的许可,当然会有用户名和密码的输入
public FtpWeb(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword)
{
//IP地址
ftpServerIP = FtpServerIP;
//Ftp文件路径
ftpRemotePath = FtpRemotePath;
//登录Ftp的用户名
ftpUserID = FtpUserID;
//登录Ftp的密码
ftpPassword = FtpPassword;
//拼接了一个文件的URL
ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
}
注:ftpRemotePath的值为ftp文件的路径不包含两边的‘/’
2.获得访问权限后,进行下载操作
/// <summary>
/// 下载
/// </summary>
/// <param name="filePath"></param>
/// <param name="fileName"></param>
public bool Download(string filePath, string fileName)
{
//定义一个FtpWebRequest的请求对象
FtpWebRequest reqFTP;
try
{
//创建一个文件流对象,并赋值(下载到本地的地址及文件名,文件生成的方式)
FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
//给请求对象赋值(要下载文件的路径)
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
//定义请求的方式(下载)
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
//指示服务器要传输的是二进制数据;false,指示数据为文本。默认值为 true
reqFTP.UseBinary = true;
//获取ftp通信的凭据
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
//返回服务器对于请求的响应
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
//获得服务器响应返回的流
Stream ftpStream = response.GetResponseStream();
//获得服务器上的接受流的长度
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
//设置字符数组的形式,从第一个字符开始读,字符大小为2048
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
//文件写入本机
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
//关闭服务
ftpStream.Close();
outputStream.Close();
response.Close();
return true;
}
catch (Exception ex)
{
Insert_Standard_ErrorLog.Insert("FtpWeb", "Download Error --> " + ex.Message);
return false;
}
}
3.上传
/// <summary>
/// 上传
/// </summary>
/// <param name="filename"></param>
public void Upload(string filename)
{
FileInfo fileInf = new FileInfo(filename);
string uri = ftpURI + fileInf.Name;
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.UseBinary = true;
reqFTP.ContentLength = fileInf.Length;
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
FileStream fs = fileInf.OpenRead();
try
{
Stream strm = reqFTP.GetRequestStream();
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0)
{
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
strm.Close();
fs.Close();
}
catch (Exception ex)
{
Insert_Standard_ErrorLog.Insert("FtpWeb", "Upload Error --> " + ex.Message);
}
}
本人以为上传和下载只是文件的流的filemode有区别,这里边的文件流的知识一直感觉很深奥,关于所有东西转化成二进制,然后又将二进制转化成所有的东西,期待哪位大牛能将宝贵的经验和理论发布出来供大家学习。 我这里的代码想必大家都知道,我的初衷是能真正的明白01世界转换的真正原理,行了不废话了,虚心接受各位的批评!