C#操作FTP, FTPHelper和SFTPHelper
1. FTPHelper
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text; public class FTPHelper
{
/// <summary>
/// 上传文件
/// </summary>
/// <param name="fileinfo">需要上传的文件</param>
/// <param name="targetDir">目标路径</param>
/// <param name="hostname">ftp地址</param>
/// <param name="username">ftp用户名</param>
/// <param name="password">ftp密码</param>
public static void UploadFile(FileInfo fileinfo, string targetDir, string hostname, string username, string password)
{
//1. check target
string target;
if (targetDir.Trim() == "")
{
return;
}
string filename = fileinfo.Name;
if (!string.IsNullOrEmpty(filename))
target = filename;
else
target = Guid.NewGuid().ToString(); //使用临时文件名 string URI = "FTP://" + hostname + "/" + targetDir + "/" + target;
///WebClient webcl = new WebClient();
System.Net.FtpWebRequest ftp = GetRequest(URI, username, password); //设置FTP命令 设置所要执行的FTP命令,
//ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;//假设此处为显示指定路径下的文件列表
ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
//指定文件传输的数据类型
ftp.UseBinary = true;
ftp.UsePassive = true; //告诉ftp文件大小
ftp.ContentLength = fileinfo.Length;
//缓冲大小设置为2KB
const int BufferSize = ;
byte[] content = new byte[BufferSize - + ];
int dataRead; //打开一个文件流 (System.IO.FileStream) 去读上传的文件
using (FileStream fs = fileinfo.OpenRead())
{
try
{
//把上传的文件写入流
using (Stream rs = ftp.GetRequestStream())
{
do
{
//每次读文件流的2KB
dataRead = fs.Read(content, , BufferSize);
rs.Write(content, , dataRead);
} while (!(dataRead < BufferSize));
rs.Close();
} }
catch (Exception ex) { }
finally
{
fs.Close();
} } ftp = null;
} /// <summary>
/// 下载文件
/// </summary>
/// <param name="localDir">下载至本地路径</param>
/// <param name="FtpDir">ftp目标文件路径</param>
/// <param name="FtpFile">从ftp要下载的文件名</param>
/// <param name="hostname">ftp地址即IP</param>
/// <param name="username">ftp用户名</param>
/// <param name="password">ftp密码</param>
public static void DownloadFile(string localDir, string FtpDir, string FtpFile, string hostname, string username, string password)
{
string URI = "FTP://" + hostname + "/" + FtpDir + "/" + FtpFile;
string tmpname = Guid.NewGuid().ToString();
string localfile = localDir + @"\" + tmpname; System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);
ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
ftp.UseBinary = true;
ftp.UsePassive = false; using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
//loop to read & write to file
using (FileStream fs = new FileStream(localfile, FileMode.CreateNew))
{
try
{
byte[] buffer = new byte[];
int read = ;
do
{
read = responseStream.Read(buffer, , buffer.Length);
fs.Write(buffer, , read);
} while (!(read == ));
responseStream.Close();
fs.Flush();
fs.Close();
}
catch (Exception)
{
//catch error and delete file only partially downloaded
fs.Close();
//delete target file as it's incomplete
File.Delete(localfile);
throw;
}
} responseStream.Close();
} response.Close();
} try
{
File.Delete(localDir + @"\" + FtpFile);
File.Move(localfile, localDir + @"\" + FtpFile); ftp = null;
ftp = GetRequest(URI, username, password);
ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile;
ftp.GetResponse(); }
catch (Exception ex)
{
File.Delete(localfile);
throw ex;
} // 记录日志 "从" + URI.ToString() + "下载到" + localDir + @"\" + FtpFile + "成功." );
ftp = null;
} /// <summary>
/// 下载文件
/// </summary>
/// <param name="localDir">下载至本地路径</param>
/// <param name="FtpDir">ftp目标文件路径</param>
/// <param name="FtpFile">从ftp要下载的文件名</param>
/// <param name="hostname">ftp地址即IP</param>
/// <param name="username">ftp用户名</param>
/// <param name="password">ftp密码</param>
public static byte[] DownloadFileBytes(string localDir, string FtpDir, string FtpFile, string hostname, string username, string password)
{
byte[] bts;
string URI = "FTP://" + hostname + "/" + FtpDir + "/" + FtpFile;
string tmpname = Guid.NewGuid().ToString();
string localfile = localDir + @"\" + tmpname; System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);
ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
ftp.UseBinary = true;
ftp.UsePassive = true; using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
//loop to read & write to file
using (MemoryStream fs = new MemoryStream())
{
try
{
byte[] buffer = new byte[];
int read = ;
do
{
read = responseStream.Read(buffer, , buffer.Length);
fs.Write(buffer, , read);
} while (!(read == ));
responseStream.Close(); //---
byte[] mbt = new byte[fs.Length];
fs.Read(mbt, , mbt.Length); bts = mbt;
//---
fs.Flush();
fs.Close();
}
catch (Exception)
{
//catch error and delete file only partially downloaded
fs.Close();
//delete target file as it's incomplete
File.Delete(localfile);
throw;
}
} responseStream.Close();
} response.Close();
} ftp = null;
return bts;
} /// <summary>
/// 搜索远程文件
/// </summary>
/// <param name="targetDir"></param>
/// <param name="hostname"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="SearchPattern"></param>
/// <returns></returns>
public static List<string> ListDirectory(string targetDir, string hostname, string username, string password, string SearchPattern)
{
List<string> result = new List<string>();
try
{
string URI = "FTP://" + hostname + "/" + targetDir + "/" + SearchPattern; System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);
ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectory;
ftp.UsePassive = true;
ftp.UseBinary = true; string str = GetStringResponse(ftp);
str = str.Replace("\r\n", "\r").TrimEnd('\r');
str = str.Replace("\n", "\r");
if (str != string.Empty)
result.AddRange(str.Split('\r')); return result;
}
catch { }
return null;
} private static string GetStringResponse(FtpWebRequest ftp)
{
//Get the result, streaming to a string
string result = "";
using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
{
long size = response.ContentLength;
using (Stream datastream = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(datastream, System.Text.Encoding.Default))
{
result = sr.ReadToEnd();
sr.Close();
} datastream.Close();
} response.Close();
} return result;
} /// 在ftp服务器上创建目录
/// </summary>
/// <param name="dirName">创建的目录名称</param>
/// <param name="ftpHostIP">ftp地址</param>
/// <param name="username">用户名</param>
/// <param name="password">密码</param>
public void MakeDir(string dirName, string ftpHostIP, string username, string password)
{
try
{
string uri = "ftp://" + ftpHostIP + "/" + dirName;
System.Net.FtpWebRequest ftp = GetRequest(uri, username, password);
ftp.Method = WebRequestMethods.Ftp.MakeDirectory; FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
response.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
} /// <summary>
/// 删除文件
/// </summary>
/// <param name="dirName">创建的目录名称</param>
/// <param name="ftpHostIP">ftp地址</param>
/// <param name="username">用户名</param>
/// <param name="password">密码</param>
public static void delFile(string dirName, string filename, string ftpHostIP, string username, string password)
{
try
{
string uri = "ftp://" + ftpHostIP + "/";
if (!string.IsNullOrEmpty(dirName)) {
uri += dirName + "/";
}
uri += filename;
System.Net.FtpWebRequest ftp = GetRequest(uri, username, password);
ftp.Method = WebRequestMethods.Ftp.DeleteFile;
FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
response.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
} /// <summary>
/// 删除目录
/// </summary>
/// <param name="dirName">创建的目录名称</param>
/// <param name="ftpHostIP">ftp地址</param>
/// <param name="username">用户名</param>
/// <param name="password">密码</param>
public void delDir(string dirName, string ftpHostIP, string username, string password)
{
try
{
string uri = "ftp://" + ftpHostIP + "/" + dirName;
System.Net.FtpWebRequest ftp = GetRequest(uri, username, password);
ftp.Method = WebRequestMethods.Ftp.RemoveDirectory;
FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
response.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
} /// <summary>
/// 文件重命名
/// </summary>
/// <param name="currentFilename">当前目录名称</param>
/// <param name="newFilename">重命名目录名称</param>
/// <param name="ftpServerIP">ftp地址</param>
/// <param name="username">用户名</param>
/// <param name="password">密码</param>
public void Rename(string currentFilename, string newFilename, string ftpServerIP, string username, string password)
{
try
{ FileInfo fileInf = new FileInfo(currentFilename);
string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
System.Net.FtpWebRequest ftp = GetRequest(uri, username, password);
ftp.Method = WebRequestMethods.Ftp.Rename; ftp.RenameTo = newFilename;
FtpWebResponse response = (FtpWebResponse)ftp.GetResponse(); response.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
} private static FtpWebRequest GetRequest(string URI, string username, string password)
{
//根据服务器信息FtpWebRequest创建类的对象
FtpWebRequest result = (FtpWebRequest)FtpWebRequest.Create(URI);
//提供身份验证信息
result.Credentials = new System.Net.NetworkCredential(username, password);
//设置请求完成之后是否保持到FTP服务器的控制连接,默认值为true
result.KeepAlive = false;
return result;
} /*
/// <summary>
/// 向Ftp服务器上传文件并创建和本地相同的目录结构
/// 遍历目录和子目录的文件
/// </summary>
/// <param name="file"></param>
private void GetFileSystemInfos(FileSystemInfo file)
{
string getDirecName = file.Name;
if (!ftpIsExistsFile(getDirecName, "192.168.0.172", "Anonymous", "") && file.Name.Equals(FileName))
{
MakeDir(getDirecName, "192.168.0.172", "Anonymous", "");
}
if (!file.Exists) return;
DirectoryInfo dire = file as DirectoryInfo;
if (dire == null) return;
FileSystemInfo[] files = dire.GetFileSystemInfos(); for (int i = 0; i < files.Length; i++)
{
FileInfo fi = files[i] as FileInfo;
if (fi != null)
{
DirectoryInfo DirecObj = fi.Directory;
string DireObjName = DirecObj.Name;
if (FileName.Equals(DireObjName))
{
UploadFile(fi, DireObjName, "192.168.0.172", "Anonymous", "");
}
else
{
Match m = Regex.Match(files[i].FullName, FileName + "+.*" + DireObjName);
//UploadFile(fi, FileName+"/"+DireObjName, "192.168.0.172", "Anonymous", "");
UploadFile(fi, m.ToString(), "192.168.0.172", "Anonymous", "");
}
}
else
{
string[] ArrayStr = files[i].FullName.Split('\\');
string finame = files[i].Name;
Match m = Regex.Match(files[i].FullName, FileName + "+.*" + finame);
//MakeDir(ArrayStr[ArrayStr.Length - 2].ToString() + "/" + finame, "192.168.0.172", "Anonymous", "");
MakeDir(m.ToString(), "192.168.0.172", "Anonymous", "");
GetFileSystemInfos(files[i]);
}
}
}
* */ /// <summary>
/// 判断ftp服务器上该目录是否存在
/// </summary>
/// <param name="dirName"></param>
/// <param name="ftpHostIP"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <returns></returns>
private bool ftpIsExistsFile(string dirName, string ftpHostIP, string username, string password)
{
bool flag = true;
try
{
string uri = "ftp://" + ftpHostIP + "/" + dirName;
System.Net.FtpWebRequest ftp = GetRequest(uri, username, password);
ftp.Method = WebRequestMethods.Ftp.ListDirectory; FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
response.Close();
}
catch (Exception)
{
flag = false;
}
return flag;
}
}
2. SFTPHelper
using System;
using Tamir.SharpSsh.jsch;
using System.Collections; public class SFTPHelper
{
private Session m_session;
private Channel m_channel;
private ChannelSftp m_sftp; //host:sftp地址 user:用户名 pwd:密码
public SFTPHelper(string host, string user, string pwd)
{
string[] arr = host.Split(':');
string ip = arr[0];
int port = 22;
if (arr.Length > 1) port = Int32.Parse(arr[1]); JSch jsch = new JSch();
m_session = jsch.getSession(user, ip, port);
MyUserInfo ui = new MyUserInfo();
ui.setPassword(pwd);
m_session.setUserInfo(ui); } //SFTP连接状态
public bool Connected { get { return m_session.isConnected(); } } //连接SFTP
public bool Connect()
{
try
{
if (!Connected)
{
m_session.connect();
m_channel = m_session.openChannel("sftp");
m_channel.connect();
m_sftp = (ChannelSftp)m_channel;
}
return true;
}
catch
{
return false;
}
} //断开SFTP
public void Disconnect()
{
if (Connected)
{
m_channel.disconnect();
m_session.disconnect();
}
} //SFTP存放文件
public bool Put(string localPath, string remotePath)
{
try
{
Tamir.SharpSsh.java.String src = new Tamir.SharpSsh.java.String(localPath);
Tamir.SharpSsh.java.String dst = new Tamir.SharpSsh.java.String(remotePath);
m_sftp.put(src, dst);
return true;
}
catch
{
return false;
}
} //SFTP获取文件
public bool Get(string remotePath, string localPath)
{
try
{
Tamir.SharpSsh.java.String src = new Tamir.SharpSsh.java.String(remotePath);
Tamir.SharpSsh.java.String dst = new Tamir.SharpSsh.java.String(localPath);
m_sftp.get(src, dst);
return true;
}
catch
{
return false;
}
}
//删除SFTP文件
public bool Delete(string remoteFile)
{
try
{
m_sftp.rm(remoteFile);
return true;
}
catch
{
return false;
}
} //获取SFTP文件列表
public ArrayList GetFileList(string remotePath, string fileType)
{
try
{
Tamir.SharpSsh.java.util.Vector vvv = m_sftp.ls(remotePath);
ArrayList objList = new ArrayList();
foreach (Tamir.SharpSsh.jsch.ChannelSftp.LsEntry qqq in vvv)
{
string sss = qqq.getFilename();
if (sss.Length > (fileType.Length + 1) && fileType == sss.Substring(sss.Length - fileType.Length))
{ objList.Add(sss); }
else { continue; }
} return objList;
}
catch
{
return null;
}
} //登录验证信息
public class MyUserInfo : UserInfo
{
String passwd;
public String getPassword() { return passwd; }
public void setPassword(String passwd) { this.passwd = passwd; } public String getPassphrase() { return null; }
public bool promptPassphrase(String message) { return true; } public bool promptPassword(String message) { return true; }
public bool promptYesNo(String message) { return true; }
public void showMessage(String message) { }
} }
C#操作FTP, FTPHelper和SFTPHelper的更多相关文章
- 使用python操作FTP上传和下载
函数释义 Python中默认安装的ftplib模块定义了FTP类,其中函数有限,可用来实现简单的ftp客户端,用于上传或下载文件,函数列举如下 ftp登陆连接 from ftplib import F ...
- C#操作FTP报错,远程服务器返回错误:(550)文件不可用(例如,未找到文件,无法访问文件)的解决方法
最近在做项目的时候需要操作ftp进行文件的上传下载,但在调用using (var response = (FtpWebResponse)FtpWebRequest.GetResponse())的时候总 ...
- Asp.Net操作FTP方法
将用户上传的附件(文件.图片等)通过FTP方式传送到另外一台服务器上,从而缓解服务器压力 1.相关的文章如下: Discuz!NT中远程附件的功能实现[FTP协议] http://www.cnblog ...
- java操作FTP的一些工具方法
java操作FTP还是很方便的,有多种开源支持,这里在apache开源的基础上自己进行了一些设计,使用起来更顺手和快捷. 思路: 1.设计FTPHandler接口,可以对ftp,sftp进行统一操作, ...
- 【转】 C#操作FTP
代码不要忘记引入命名空间using System.Net;using System.IO;下面的几个步骤包括了使用FtpWebRequest类实现ftp功能的一般过程1.创建一个FtpWebReque ...
- C# 操作FTP
操作FTP管理类: using System; using System.Collections.Generic; using System.Text; using System.Net; using ...
- ftp客户端自动同步 Windows系统简单操作ftp客户端自动同步
服务器管理工具它是一款功能强大的服务器集成管理器,包含win系统和linux系统的批量连接,vnc客户端,ftp客户端等等实用功能.我们可以使用这款软件的ftp客户端定时上传下载的功能来进实现ftp客 ...
- 【转载】C#工具类:FTP操作辅助类FTPHelper
FTP是一个8位的客户端-服务器协议,能操作任何类型的文件而不需要进一步处理,就像MIME或Unicode一样.可以通过C#中的FtpWebRequest类.NetworkCredential类.We ...
- 【C#】工具类-FTP操作封装类FTPHelper
转载:http://blog.csdn.net/gdjlc/article/details/11968477 using System; using System.Collections.Generi ...
随机推荐
- OSGI.NET 插件无法启动之情景一
关于osgi.net 的使用网上也有不少的资料,最近在使用osgi.net 开发插件的时候,遇到了这样的bug,造成插件甚至整个项目都无法启动,异常的具体消息如下: Could not find a ...
- 学习记录 java 值类型和引用类型的知识
1. Java中值类型和引用类型的不同? [定义] 引用类型表示你操作的数据是同一个,也就是说当你传一个参数给另一个方法时,你在另一个方法中改变这个变量的值, 那么调用这个方法是传入的变量的值也将改变 ...
- Cnetos7下,已经能访问tomcat
进入/usr/local/apache-tomcat-8.0.24/bin 中 执行:./startup.sh开启tomcat 再执行如下 systemctl stop firewalld.servi ...
- 再论App的安全性
现代人早已脱离不了智能手机,几乎人手一机,常见人边走边滑,着实危险.大家用手机App购物,用网银App付费,用股票App下单炒股,太方便了所以成了家常便饭. 没错,就是因为太方便,所以大多只会留意好不 ...
- Android手机与计算机间的”信任关系”
在iDevices(如iPhone.iPad等等)的取证方面,那个代表”信任关系”的plist无疑是最为关键的迹证,只要有了它,哪怕是最新机型的iDevice及最新版的iOS,且有着指纹保护或pass ...
- Can Live View boot up images acquired from 64bit OS evidence?
Some said Live View could only boot up images acquired from 32bit OS evidence. I have to say that it ...
- poj1001_Exponentiation
这题真是超级大模拟.好繁琐,自己写的打数加法,乘法,写的比我大一时候写的要好很多,大一是借助C++里面的string来写的,这把只用了C,浇一次就ac了,挺开心的,不过写了2个小时啊.注意零的处理.大 ...
- 图片无法显示,载入制定url失败
今天要做一个图片列表,因为是临时用的,就把图片存放在了img/linshi文件夹下,但是在网页上总是显示不了,提示载入制定url失败, 找了半天,把图片放在上级目录,img下立刻就能访问了.
- [转]基于AnyCAD的准双曲面齿轮建模
基于AnyCAD的准双曲面齿轮建模 作者:谨阳 (文章来源:http://www.opencascade.net/ask/?/article/6) 摘要:根据准双面齿轮的加工方法和传动特性,对准双面齿 ...
- PO、BO、VO、DTO、POJO、DAO的区别
PO: 基本上就是Entity了 persistant object持久对象 最形象的理解就是一个PO就是数据库中的一条记录. 好处是可以把一条记录作为一个对象处理,可以方便的转为其它对象. ---- ...