62,046
社区成员
发帖
与我相关
我的任务
分享
class FtpClass
{
/// <summary>
/// ftp操作
/// ftpUrl--ftp的地址,user--ftp用户名 password--ftp密码
/// </summary>
FtpWebRequest request;
//string ftpUrl = string.Empty;
string user = "ALLTANG01\\ASPNET";
string password = "";
/// <summary>
/// 二进制数据流操作
/// myStream--读取数据,length--数据流长度,fileData--二进制数据
/// file--要传输文件全名,fileName--要传输文件名称,fileType--要传输文件的后缀名
/// </summary>
int length;
byte[] fileData;
string file = string.Empty;
string fileName = string.Empty;
string fileType = string.Empty;
/// <summary>
/// 打开要传输的文件
/// </summary>
/// <param name="filePath">文件路径</param>
public void OpenFile(string filePath)
{
if (!File.Exists(filePath))
{
return;
}
fileName = filePath.Substring(filePath.LastIndexOf("\\") + 1, (filePath.LastIndexOf(".") - filePath.LastIndexOf("\\") - 1));
fileType = filePath.Substring(filePath.LastIndexOf(".") + 1, (filePath.Length - filePath.LastIndexOf(".") - 1));
file = fileName + "." + fileType;
fileData = File.ReadAllBytes(filePath);
length = fileData.Length;
}
/// <summary>
/// 连接并上传ftp服务
/// </summary>
/// <param name="ftpUrl">ftp地址</param>
public string Connect(string filePath, string ftpUrl)
{
// 分析需要上传的文件
this.OpenFile(filePath);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + 实际IP + file));
// FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + "localhost/"+ftpUrl+ file));
// ftp用户名和密码
request.Credentials = new NetworkCredential(user, password);
// 默认为true,连接不会被关闭,在一个命令之后被执行
request.KeepAlive = false;
// 指定执行什么命令
request.Method = WebRequestMethods.Ftp.UploadFile;
// 指定数据传输类型
request.UseBinary = true;
//
request.Credentials = new NetworkCredential(user, password);
// 上传文件时通知服务器文件的大小
request.ContentLength = fileData.Length;
request.Proxy = null;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileData, 0, fileData.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
// MessageBox.Show("Upload File Complete, status:" + response.StatusCode + "--" + response.StatusDescription);
response.Close();
return "Upload File Complete, status:" + response.StatusCode + "--" + response.StatusDescription;
}
}
以上是代码