c# ftp 上传文件 与 下载文件

时间:2023-03-09 13:19:07
c# ftp 上传文件 与 下载文件

接着上一篇说。

上一篇说了根据配置文件获取路径,并判断路径在服务器中是否存在。如果不存在则在服务器中建立一个。

然后就是往路径下面传输文件了。、

代码:

 //连接ftp
private void Connect(String path)
{
// 根据uri创建FtpWebRequest对象
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
// 指定数据传输类型
reqFTP.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
reqFTP.UseBinary = true;
reqFTP.UsePassive = false;
// ftp用户名和密码
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
}
public void Upload(string filename) //上面的代码实现了从ftp服务器上载文件的功能
{
FileInfo fileInf = new FileInfo(filename);
string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
Connect(uri);//连接
// 默认为true,连接不会被关闭
// 在一个命令之后被执行
reqFTP.KeepAlive = false;
// 指定执行什么命令
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
// 上传文件时通知服务器文件的大小
reqFTP.ContentLength = fileInf.Length;
// 缓冲大小设置为kb
int buffLength = ;
byte[] buff = new byte[buffLength];
int contentLen;
// 打开一个文件流(System.IO.FileStream) 去读上传的文件
FileStream fs = fileInf.OpenRead();
try
{
int allbye = (int)fileInf.Length;
int startbye = ;// 把上传的文件写入流
Stream strm = reqFTP.GetRequestStream();//根据服务器的FTP配置不同,要使用不同的模式,否则会报错
// 每次读文件流的kb
contentLen = fs.Read(buff, , buffLength);// 流内容没有结束
while (contentLen != )
{
// 把内容从file stream 写入upload stream
strm.Write(buff, , contentLen);
contentLen = fs.Read(buff, , buffLength);
startbye += buffLength;
}// 关闭两个流
strm.Close();
fs.Close();
}
catch (Exception ex)
{
this.WriteLog("上传失败,原因: " + ex.Message); fs.Close();
} }
/// <summary>
/// 下载文件
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public Byte[] Download(string fileName)/**/////上面的代码实现了从ftp服务器下载文件的功能
{
Byte[] rtn = null;
try
{
long allbye = (long)GetFileSize(fileName);
string url = "ftp://" + ftpServerIP + "/" + fileName;
Connect(url);//连接
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.KeepAlive = false;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = ;
int readCount = ;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, , bufferSize);
MemoryStream mstream = new MemoryStream();
int startbye = ;
while (readCount > )
{
mstream.Write(buffer, , readCount); readCount = ftpStream.Read(buffer, , bufferSize);
startbye += readCount;
}
rtn = mstream.ToArray();
ftpStream.Close();
response.Close();
mstream.Close();
return rtn;
}
catch (Exception ex)
{
//errorinfo = string.Format("因{0},无法下载", ex.Message);
throw new Exception("下载失败,原因: " + ex.Message);
}
}