标题:
c# 操作FTP文件类(1)
[打印本页]
作者:
look_w
时间:
2019-4-17 18:31
标题:
c# 操作FTP文件类(1)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
namespace RCP.Web.Common
{
/// <summary>
/// FTP传输工具对象
/// </summary>
public sealed class FTPUtils
{
private string _serverIP;
private string _userID;
private string _password;
private FtpWebRequest reqFTP;
public FTPUtils(string serverIP, string userID, string password)
{
this._password = password;
this._serverIP = serverIP;
this._userID = userID;
}
#region 连接
/// <summary>
/// 连接
/// </summary>
/// <param name="path"></param>
public void Connect(string path)//连接ftp
{
// 根据uri创建FtpWebRequest对象
if (reqFTP != null)
{
try
{
reqFTP.Abort();
}
catch { }
}
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
// 指定数据传输类型
reqFTP.UseBinary = true;
// ftp用户名和密码
reqFTP.Credentials = new NetworkCredential(_userID, _password);
}
#endregion
#region 获取文件列表
/// <summary>
/// 获取文件列表
/// </summary>
/// <param name="path"></param>
/// <param name="method"></param>
/// <returns></returns>
private string[] GetFileList(string path, string method)//上面的代码示例了如何从ftp服务器上获得文件列表
{
StringBuilder result = new StringBuilder();
try
{
Connect(path);
reqFTP.Method = method;
using (WebResponse response = reqFTP.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
{
string content = reader.ReadToEnd();
if (!string.IsNullOrEmpty(content))
{
return content.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
}
return null;
}
}
}
catch (Exception ex)
{
return null;
}
}
public string[] GetFileList(string path)//上面的代码示例了如何从ftp服务器上获得文件列表
{
return GetFileList("ftp://" + _serverIP + "/" + path, WebRequestMethods.Ftp.ListDirectory);
}
public string[] GetFileList()//上面的代码示例了如何从ftp服务器上获得文件列表
{
return GetFileList("ftp://" + _serverIP + "/", WebRequestMethods.Ftp.ListDirectory);
}
#endregion
#region 上传文件
/// <summary>
/// 上传文件
/// </summary>
/// <param name="filename">上传文件的全路径</param>
/// <param name="dirName">文件夹名,根目录请填写"",不存在则自动创建</param>
/// <param name="isGuidName">是否使用GUID文件名,默认为true</param>
/// <returns></returns>
public string Upload(string filename, string dirName, bool isGuidName) //上面的代码实现了从ftp服务器上载文件的功能
{
bool isGuid = true;
string savaName = "";
isGuid = isGuidName;
dirName = dirName.Trim('/').TrimEnd('/');
string path = this._serverIP.Replace("\\", "/");
FileInfo fileInf = new FileInfo(filename);
if (isGuid)
{
string[] temp = fileInf.Name.Split('.');
savaName = Guid.NewGuid() + "." + temp[temp.Length - 1];
}
else
{
savaName = fileInf.Name;
}
MakeMultipleDir(dirName);
savaName = dirName == "" ? savaName : dirName + "/" + savaName;
string uri = "ftp://" + path + "/" + savaName;
Connect(uri);//连接
// 默认为true,连接不会被关闭
// 在一个命令之后被执行
reqFTP.KeepAlive = false;
// 指定执行什么命令
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
// 上传文件时通知服务器文件的大小
reqFTP.ContentLength = fileInf.Length;
// 缓冲大小设置为kb
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
// 打开一个文件流(System.IO.FileStream) 去读上传的文件
FileStream fs = fileInf.OpenRead();
try
{
// 把上传的文件写入流
Stream strm = reqFTP.GetRequestStream();
// 每次读文件流的kb
contentLen = fs.Read(buff, 0, buffLength);
// 流内容没有结束
while (contentLen != 0)
{
// 把内容从file stream 写入upload stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
// 关闭两个流
strm.Close();
fs.Close();
//errorinfo = "完成";
return "/" + savaName;
}
catch (Exception ex)
{
//errorinfo = string.Format("因{0},无法完成上传", ex.Message);
return "";
}
}
/// <summary>
/// 直接传数据流的方式
/// </summary>
/// <param name="streamRead">数据流</param>
/// <param name="dirName">ftp路径</param>
/// <param name="fileName">文件名称</param>
/// <returns></returns>
public string UpdateStream(Stream streamRead, string dirName, string fileName)
{
string savaName = "";
dirName = dirName.Trim('/').TrimEnd('/');
string path = this._serverIP.Replace("\\", "/");
MakeMultipleDir(dirName);
savaName = dirName == "" ? savaName : dirName + "/" + fileName;
string uri = "ftp://" + path + "/" + savaName;
Connect(uri);//连接
// 默认为true,连接不会被关闭
// 在一个命令之后被执行
reqFTP.KeepAlive = false;
// 指定执行什么命令
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
// 上传文件时通知服务器文件的大小
reqFTP.ContentLength = streamRead.Length;
// 缓冲大小设置为5kb
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
try
{
Stream streamWrite = reqFTP.GetRequestStream();
streamRead.Flush();
streamRead.Position = 0;
contentLen = streamRead.Read(buff, 0, buffLength);
while (contentLen != 0)
{
streamWrite.Write(buff, 0, contentLen);
contentLen = streamRead.Read(buff, 0, buffLength);
}
// 关闭两个流
streamWrite.Close();
return "/"+savaName;
}
catch (Exception)
{
return "";
}
}
/// <summary>
/// 上传图片
/// </summary>
/// <param name="img">图片</param>
/// <param name="dirName">ftp地址</param>
/// <param name="fileName">文件名称</param>
/// <param name="imgFormat">图片格式</param>
/// <returns></returns>
public string UploadImg(Image img, string dirName, string fileName,ImageFormat imgFormat)
{
//获取图片流
MemoryStream streamRead = new MemoryStream();
img.Save(streamRead, imgFormat);
return UpdateStream(streamRead, dirName, fileName);
}
#endregion
#region 删除文件
/// <summary>
/// 删除文件
/// </summary>
/// <param name="fileName">文件的相对路径</param>
public bool DeleteFileName(string fileName)
{
try
{
//FileInfo fileInf = new FileInfo(fileName);
string uri = "ftp://" + _serverIP + "/" + fileName;
Connect(uri);//连接
// 默认为true,连接不会被关闭
// 在一个命令之后被执行
reqFTP.KeepAlive = false;
// 指定执行什么命令
reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
response.Close();
return true;
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message, "删除错误");
return false;
}
}
#endregion
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/)
Powered by Discuz! 7.0.0