FTP上传类

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace FTPHelper
{
//本文由MosCMS贡献
public class FTP_Class
{
private string ftpServerIP;
private string ftpUserID;
private string ftpPassword;
FtpWebRequest reqFTP;
public void Connecttest(string ftpServerIP, string ftpUserId, string ftppassword)
{
// 根据uri创建FtpWebRequest对象
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP));
// 指定数据传输类型
reqFTP.UseBinary = true;
ftpUserID = ftpUserId;
ftpPassword = ftppassword;
// ftp用户名和密码
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

}
#region 连接
private void Connect(String path)//连接ftp
{
// 根据uri创建FtpWebRequest对象
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
// 指定数据传输类型
reqFTP.UseBinary = true;
// ftp用户名和密码
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
}
#endregion
#region ftp登录信息
public void FtpUpDown(string ftpServerIP, string ftpUserID, string ftpPassword)
{
this.ftpServerIP = ftpServerIP;
this.ftpUserID = ftpUserID;
this.ftpPassword = ftpPassword;
}
#endregion
#region 获取文件列表

/// 获取文件列表
private string[] GetFileList(string path, string WRMethods)//上面的代码示例了如何从ftp服务器上获得文件列表
{
string[] downloadFiles;
StringBuilder result = new StringBuilder();
try
{
Connect(path);
reqFTP.Method = WRMethods;
WebResponse response = reqFTP.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);//中文文件名
string line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
// to remove the trailing ‘\n‘
result.Remove(result.ToString().LastIndexOf(‘\n‘), 1);
reader.Close();
response.Close();
return result.ToString().Split(‘\n‘);
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
downloadFiles = null;
return downloadFiles;
}
}
public string[] GetFileList(string path)//上面的代码示例了如何从ftp服务器上获得文件列表
{
return GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectory);
}
public string[] GetFileList()//上面的代码示例了如何从ftp服务器上获得文件列表
{
return GetFileList("ftp://" + ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectory);
}
#endregion

#region 上传文件
public bool Upload(string filename, string path, out string errorinfo) //上面的代码实现了从ftp服务器上载文件的功能
{
path = path.Replace("\\", "/");
FileInfo fileInf = new FileInfo(filename);
string uri = "ftp://" + path + "/" + fileInf.Name;
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 true;
}
catch (Exception ex)
{
errorinfo = string.Format("因{0},无法完成上传", ex.Message);
return false;
}
}
#endregion
#region 续传文件
public bool Upload(string filename, long size, string path, out string errorinfo) //上面的代码实现了从ftp服务器上载文件的功能
{
path = path.Replace("\\", "/");
FileInfo fileInf = new FileInfo(filename);
//string uri = "ftp://" + path + "/" + fileInf.Name;
string uri = "ftp://" + path;
Connect(uri);//连接
// 默认为true,连接不会被关闭
// 在一个命令之后被执行
reqFTP.KeepAlive = false;
// 指定执行什么命令
reqFTP.Method = WebRequestMethods.Ftp.AppendFile;
// 上传文件时通知服务器文件的大小
reqFTP.ContentLength = fileInf.Length;
// 缓冲大小设置为kb
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
// 打开一个文件流(System.IO.FileStream) 去读上传的文件
FileStream fs = fileInf.OpenRead();
try
{
StreamReader dsad = new StreamReader(fs);
fs.Seek(size, SeekOrigin.Begin);
// 把上传的文件写入流
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 true;
}
catch (Exception ex)
{
errorinfo = string.Format("因{0},无法完成上传", ex.Message);
return false;
}
}
#endregion
#region 下载文件
public bool Download(string ftpfilepath, string filePath, string fileName, out string errorinfo)////上面的代码实现了从ftp服务器下载文件的功能
{
try
{
filePath = filePath.Replace("我的电脑\\", "");
String onlyFileName = Path.GetFileName(fileName);
string newFileName = filePath + onlyFileName;
if (File.Exists(newFileName))
{
errorinfo = string.Format("本地文件{0}已存在,无法下载", newFileName);
return false;
}
ftpfilepath = ftpfilepath.Replace("\\", "/");
string url = "ftp://" + ftpfilepath;
Connect(url);//连接

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];
readCount = ftpStream.Read(buffer, 0, bufferSize);
FileStream outputStream = new FileStream(newFileName, FileMode.Create);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
errorinfo = "";
return true;
}
catch (Exception ex)
{
errorinfo = string.Format("因{0},无法下载", ex.Message);
return false;
}
}
#endregion
#region 删除文件
public void DeleteFileName(string fileName)
{
try
{
FileInfo fileInf = new FileInfo(fileName);
string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
Connect(uri);//连接
// 默认为true,连接不会被关闭
// 在一个命令之后被执行
reqFTP.KeepAlive = false;
// 指定执行什么命令
reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
response.Close();
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message, "删除错误");
}
}
#endregion
#region 在ftp上创建目录
public void MakeDir(string dirName)
{
try
{
string uri = "ftp://" + ftpServerIP + "/" + dirName;
Connect(uri);//连接
reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
response.Close();
}
catch (Exception ex)
{
// MessageBox.Show(ex.Message);
}
}
#endregion
#region 删除ftp上目录
public void delDir(string dirName)
{
try
{
string uri = "ftp://" + ftpServerIP + "/" + dirName;
Connect(uri);//连接
reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
response.Close();
}
catch (Exception ex)
{
}
}
#endregion
#region 获得ftp上文件大小
public long GetFileSize(string filename)
{
long fileSize = 0;
filename = filename.Replace("\\", "/");
try
{
// FileInfo fileInf = new FileInfo(filename);

//string uri1 = "ftp://" + ftpServerIP + "/" + fileInf.Name;
// string uri = filename;
string uri = "ftp://" + filename;
Connect(uri);//连接
reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
fileSize = response.ContentLength;
response.Close();
}
catch (Exception ex)
{
// MessageBox.Show(ex.Message);
}
return fileSize;
}
#endregion
#region ftp上文件改名
public void Rename(string currentFilename, string newFilename)
{
try
{
FileInfo fileInf = new FileInfo(currentFilename);
string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
Connect(uri);//连接
reqFTP.Method = WebRequestMethods.Ftp.Rename;
reqFTP.RenameTo = newFilename;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
//Stream ftpStream = response.GetResponseStream();
//ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
// MessageBox.Show(ex.Message);
}
}
#endregion
#region 获得文件明晰
public string[] GetFilesDetailList()
{
return GetFileList("ftp://" + ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectoryDetails);
}
public string[] GetFilesDetailList(string path)
{
path = path.Replace("\\", "/");
return GetFileList("ftp://" + path, WebRequestMethods.Ftp.ListDirectoryDetails);
}
#endregion
}
}

时间: 2024-08-03 07:38:22

FTP上传类的相关文章

FTP上传指定文件夹及其文件到服务器

1.在服务器端的IIS上建立一个FTP站点 注意事项:路径关联到你要存放(上传内容)的文件夹名称: 指定这个FTP站点的ip地址和端口号 2.本地准备代码 -------------------------------2.1上传类--------------------------------------------------------- public class Up    {        /// <summary>        ///   上传文件菜单        /// <

FTP 上传下载工具类

import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.SocketException; import o

java ftp 上传下载工具类

1 package com.mohecun.utils; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.FileNotFoundException; 6 import java.io.FileOutputStream; 7 import java.io.IOException; 8 import java.io.InputStream; 9 import java.io.OutputStre

高可用的Spring FTP上传下载工具类(已解决上传过程常见问题)

前言 最近在项目中需要和ftp服务器进行交互,在网上找了一下关于ftp上传下载的工具类,大致有两种. 第一种是单例模式的类. 第二种是另外定义一个Service,直接通过Service来实现ftp的上传下载. 这两种感觉都有利弊. 第一种实现了代码复用,但是配置信息全需要写在类中,维护比较复杂. 第二种如果是spring框架,可以通过propertis文件,动态的注入配置信息,但是又不能代码复用. 所以我打算自己实现一个工具类,来把上面的两种优点进行整合.顺便把一些上传过程中一些常见的问题也给解

再看ftp上传文件

前言 去年在项目中用到ftp上传文件,用FtpWebRequest和FtpWebResponse封装一个帮助类,这个在网上能找到很多,前台使用Uploadify控件,然后在服务器上搭建Ftp服务器,在本地测试程序上传到ftp服务器一点问题都没有,奇怪的是当发布Web和ftp到同一个IIS下,上传文件时程序直接卡死,然后页面卡死,后来我又发现把Web和ftp分开发布在两台机器上问题又得到解决,所以当时放弃了这个方案. 再看ftp上传文件 前几天偶然看到Wolfy写到一个项目总结,其中提到了用Ser

C# FTP上传文件至服务器代码

C# FTP上传文件至服务器代码 /// <summary> /// 上传文件 /// </summary> /// <param name="fileinfo">需要上传的文件</param> /// <param name="targetDir">目标路径</param> /// <param name="hostname">ftp地址</param&g

SpringMvc + Jsp+ 富文本 kindeditor 进行 图片ftp上传nginx服务器 实现

一:html 原生态的附件上传 二:实现逻辑分析: 1.1.1 需求分析 Common.js 1.绑定事件 2.初始化参数 3.上传图片的url: /pic/upload 4.上图片参数名称: uploadFile 5.返回结果数据类型json 参考文档: http://kindeditor.net/docs/upload.html 返回格式(JSON) 1 //成功时 2 3 { 4 5 "error" : 0, 6 7 "url" : "http://

简单的FTP上传下载(java实现)

/** *阅读前请自己在win7上建立FTP主机 *具体步骤如:http://jingyan.baidu.com/article/574c5219d466c36c8d9dc138.html * 然后将以下FTP,username,password分别改成你的FTP ip地址 用户名 密码即可 * 本例子用了apche的commons-net-3.3.jar以方便FTP的访问 请手动buid -path * 待完成版 刷新按钮 登录 都还没有做 而且上传 下载 完成后都需要重新运行 * 2014-

ftp上传

/** * FTP上传工具类 * */public class FtpUtil {static Logger logger = Logger.getLogger(FtpUtil.class.getName()); private String ip; private String username; private String password; private int port = -1; private String path; private OutputStream os = null