FTP上传文件夹
文件上传类
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks; namespace ImageResize
{
public class FtpClient
{
public string ftpUser = string.Empty;
public string ftpPassword = string.Empty;
public string ftpRootURL = string.Empty;
public bool isFlag = true;
public string baseFolderPath = null; public FtpClient(string url, string userid, string password)
{
this.ftpUser = userid;
this.ftpPassword = password;
this.ftpRootURL = url;
} /// <summary>
/// 文件夹上传
/// </summary>
/// <param name="sourceFolder"></param>
/// <param name="destFolder">ftpRootUrl + ftpPath</param>
/// <returns></returns>
public bool foldersUpload(string sourceFolder, string destFolder, string detailFolder)
{
bool isFolderFlag = false;
if (isFlag)
{
baseFolderPath = sourceFolder.Substring(, sourceFolder.LastIndexOf("\\"));
isFlag = false;
} string selectFolderName = sourceFolder.Replace(baseFolderPath, "").Replace("\\", "/"); if (selectFolderName != null)
{
string ftpDirectory = destFolder + selectFolderName;
if (ftpDirectory.LastIndexOf('/') < ftpDirectory.Length - )
{
ftpDirectory = ftpDirectory + "/";
}
if (!FtpDirectoryIsNotExists(ftpDirectory))
{
CreateFtpDirectory(ftpDirectory);
}
} try
{
string[] directories = Directory.EnumerateDirectories(sourceFolder).ToArray();
if (directories.Length > )
{
foreach (string d in directories)
{
foldersUpload(d, destFolder, sourceFolder.Replace(baseFolderPath, "").Replace("\\","/"));
}
} string[] files = Directory.EnumerateFiles(sourceFolder).ToArray();
if (files.Length > )
{
foreach (string s in files)
{ string fileName = s.Substring(s.LastIndexOf("\\")).Replace("\\", "/"); if(selectFolderName.Contains("/"))
{
if(selectFolderName.LastIndexOf('/') < selectFolderName.Length -)
{
selectFolderName = selectFolderName + '/';
} }
ftpRootURL = destFolder; fileUpload(new FileInfo(s), selectFolderName , fileName.Substring(,fileName.Length -)); }
}
isFolderFlag = true; }
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
return isFolderFlag;
} /// <summary>
/// 上传
/// </summary>
/// <param name="localFile">本地文件绝对路径</param>
/// <param name="ftpPath">上传到ftp的路径</param>
/// <param name="ftpFileName">上传到ftp的文件名</param>
public bool fileUpload(FileInfo localFile, string ftpPath, string ftpFileName)
{
bool success = false;
FtpWebRequest ftpWebRequest = null; FileStream localFileStream = null;
Stream requestStream = null; try
{
// 检查FTP目标存放目录是否存在
// 1.1 ftp 上目标目录
string destFolderPath = ftpRootURL + ftpPath; if (!FtpDirectoryIsNotExists(destFolderPath))
{
CreateFtpDirectory(destFolderPath);
} string uri = ftpRootURL + ftpPath + ftpFileName;
ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
ftpWebRequest.UseBinary = true; ftpWebRequest.KeepAlive = false;
ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpWebRequest.ContentLength = localFile.Length; int buffLength = ;
byte[] buff = new byte[buffLength];
int contentLen; localFileStream = localFile.OpenRead();
requestStream = ftpWebRequest.GetRequestStream(); contentLen = localFileStream.Read(buff, , buffLength);
while (contentLen != )
{
// 把内容从file stream 写入upload stream
requestStream.Write(buff, , contentLen);
contentLen = localFileStream.Read(buff, , buffLength);
} success = true;
}
catch (Exception)
{
success = false;
}
finally
{
if (requestStream != null)
{
requestStream.Close();
}
if (localFileStream != null)
{
localFileStream.Close();
}
} return success;
} /// <summary>
/// 上传文件
/// </summary>
/// <param name="localPath">本地文件地址(没有文件名)</param>
/// <param name="localFileName">本地文件名</param>
/// <param name="ftpPath">上传到ftp的路径</param>
/// <param name="ftpFileName">上传到ftp的文件名</param>
public bool fileUpload(string localPath, string localFileName, string ftpPath, string ftpFileName)
{
bool success = false;
try
{
FileInfo localFile = new FileInfo(localPath + localFileName);
if (localFile.Exists)
{
success = fileUpload(localFile, ftpPath, ftpFileName);
}
else
{
success = false;
}
}
catch (Exception)
{
success = false;
}
return success;
} /// <summary>
/// 下载文件
/// </summary>
/// <param name="localPath">本地文件地址(没有文件名)</param>
/// <param name="localFileName">本地文件名</param>
/// <param name="ftpPath">下载的ftp的路径</param>
/// <param name="ftpFileName">下载的ftp的文件名</param>
public bool fileDownload(string localPath, string localFileName, string ftpPath, string ftpFileName)
{
bool success = false;
FtpWebRequest ftpWebRequest = null;
FtpWebResponse ftpWebResponse = null;
Stream ftpResponseStream = null;
FileStream outputStream = null;
try
{
outputStream = new FileStream(localPath + localFileName, FileMode.Create);
string uri = ftpRootURL + ftpPath + ftpFileName;
ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
ftpWebRequest.UseBinary = true;
ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile;
ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
ftpResponseStream = ftpWebResponse.GetResponseStream();
long contentLength = ftpWebResponse.ContentLength;
int bufferSize = ;
byte[] buffer = new byte[bufferSize];
int readCount;
readCount = ftpResponseStream.Read(buffer, , bufferSize);
while (readCount > )
{
outputStream.Write(buffer, , readCount);
readCount = ftpResponseStream.Read(buffer, , bufferSize);
}
success = true;
}
catch (Exception)
{
success = false;
}
finally
{
if (outputStream != null)
{
outputStream.Close();
}
if (ftpResponseStream != null)
{
ftpResponseStream.Close();
}
if (ftpWebResponse != null)
{
ftpWebResponse.Close();
}
}
return success;
} /// <summary>
/// 重命名
/// </summary>
/// <param name="ftpPath">ftp文件路径</param>
/// <param name="currentFilename"></param>
/// <param name="newFilename"></param>
public bool fileRename(string ftpPath, string currentFileName, string newFileName)
{
bool success = false;
FtpWebRequest ftpWebRequest = null;
FtpWebResponse ftpWebResponse = null;
Stream ftpResponseStream = null;
try
{
string uri = ftpRootURL + ftpPath + currentFileName;
ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
ftpWebRequest.UseBinary = true;
ftpWebRequest.Method = WebRequestMethods.Ftp.Rename;
ftpWebRequest.RenameTo = newFileName; ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
ftpResponseStream = ftpWebResponse.GetResponseStream(); }
catch (Exception)
{
success = false;
}
finally
{
if (ftpResponseStream != null)
{
ftpResponseStream.Close();
}
if (ftpWebResponse != null)
{
ftpWebResponse.Close();
}
}
return success;
} /// <summary>
/// 消除文件
/// </summary>
/// <param name="filePath"></param>
public bool fileDelete(string ftpPath, string ftpName)
{
bool success = false;
FtpWebRequest ftpWebRequest = null;
FtpWebResponse ftpWebResponse = null;
Stream ftpResponseStream = null;
StreamReader streamReader = null;
try
{
string uri = ftpRootURL + ftpPath + ftpName;
ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
ftpWebRequest.KeepAlive = false;
ftpWebRequest.Method = WebRequestMethods.Ftp.DeleteFile;
ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
long size = ftpWebResponse.ContentLength;
ftpResponseStream = ftpWebResponse.GetResponseStream();
streamReader = new StreamReader(ftpResponseStream);
string result = String.Empty;
result = streamReader.ReadToEnd(); success = true;
}
catch (Exception)
{
success = false;
}
finally
{
if (streamReader != null)
{
streamReader.Close();
}
if (ftpResponseStream != null)
{
ftpResponseStream.Close();
}
if (ftpWebResponse != null)
{
ftpWebResponse.Close();
}
}
return success;
} /// <summary>
/// 文件存在检查
/// </summary>
public bool fileCheckExist(string destFolderPath, string fileName)
{
bool success = false;
FtpWebRequest ftpWebRequest = null;
WebResponse webResponse = null;
StreamReader reader = null;
try
{ ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(destFolderPath));
ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
ftpWebRequest.Method = WebRequestMethods.Ftp.ListDirectory;
ftpWebRequest.KeepAlive = false;
webResponse = ftpWebRequest.GetResponse();
reader = new StreamReader(webResponse.GetResponseStream());
string line = reader.ReadLine();
while (line != null)
{
string ftpName = "test.jpg";
if (line == ftpName)
{
success = true;
break;
}
line = reader.ReadLine();
}
}
catch (Exception)
{
success = false;
}
finally
{
if (reader != null)
{
reader.Close();
}
if (webResponse != null)
{
webResponse.Close();
}
}
return success;
} /// <summary>
/// 创建FTP文件目录
/// </summary>
/// <param name="ftpDirectory">ftp服务器上的文件目录</param>
public void CreateFtpDirectory(string ftpDirectory)
{
try
{
FtpWebRequest ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpDirectory));
ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
ftpWebRequest.UseBinary = true;
ftpWebRequest.KeepAlive = false;
ftpWebRequest.Method = WebRequestMethods.Ftp.MakeDirectory; FtpWebResponse respFTP = (FtpWebResponse)ftpWebRequest.GetResponse();
respFTP.Close();
}
catch (Exception ex)
{
Debug.WriteLine("FTP创建目录失败" + ex.Message);
} } /// <summary>
/// 获取目录下的详细信息
/// </summary>
/// <param name="localDir">本机目录</param>
/// <returns></returns>
public List<List<string>> GetDirDetails(string localDir)
{
List<List<string>> infos = new List<List<string>>();
try
{
infos.Add(Directory.GetFiles(localDir).ToList());
infos.Add(Directory.GetDirectories(localDir).ToList());
for (int i = ; i < infos[].Count; i++)
{
int index = infos[][i].LastIndexOf(@"\");
infos[][i] = infos[][i].Substring(index + );
}
}
catch(Exception ex)
{
Debug.WriteLine(ex.Message);
}
return infos;
} public void UploadDirectory(string localDir, string ftpPath, string dirName, string ftpUser, string ftpPassword)
{
if (ftpUser == null)
{
ftpUser = "";
}
if (ftpPassword == null)
{
ftpPassword = "";
} string dir = localDir + dirName + @"\"; if (!Directory.Exists(dir))
{
return;
} //if (!CheckDirectoryExist(ftpPath, dirName))
//{
// MakeDir(ftpPath, dirName); //} List<List<string>> infos = GetDirDetails(dir); //获取当前目录下的所有文件和文件夹
//先上传文件
// MyLog.ShowMessage(dir + "下的文件数:" + infos[0].Count.ToString());
for (int i = ; i < infos[].Count; i++)
{
Console.WriteLine(infos[][i]);
// UpLoadFile(dir + infos[0][i], ftpPath + dirName + @"/" + infos[0][i], ftpUser, ftpPassword);
}
//再处理文件夹
// MyLog.ShowMessage(dir + "下的目录数:" + infos[1].Count.ToString());
for (int i = ; i < infos[].Count; i++)
{
UploadDirectory(dir, ftpPath + dirName + @"/", infos[][i], ftpUser, ftpPassword);
}
} /// <summary>
/// 判断Ftp上待上传文件存放的(文件夹)目录是否存在
/// 注意事项:目录结构的最后一个字符一定要是一个斜杠
/// </summary>
/// <param name="destFtpFolderPath">Ftp服务器上存放待上传文件的目录</param>
private bool FtpDirectoryIsNotExists(string destFolderPath)
{
try
{
var request = (FtpWebRequest)WebRequest.Create(destFolderPath);
request.Credentials = new NetworkCredential(ftpUser, ftpPassword);
request.Method = WebRequestMethods.Ftp.ListDirectory;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
response.Close();
return false;
}
else
{
response.Close();
}
}
return true;
} /// <summary>
/// 解析文件所在的路径(即当前文件所在的文件位置)
/// </summary>
/// <param name="destFilePath">需要存储在FTP服务器上的文件路径,如:ftp://192.168.1.100/LocalUser/picture1.jpg</param>
/// <returns></returns>
public string FtpParseDirectory(string destFilePath)
{
return destFilePath.Substring(, destFilePath.LastIndexOf("/"));
} // 验证文件类型
public bool IsAllowableFileType(string fileName)
{
//从web.config读取判断文件类型限制
string stringstrFileTypeLimit = string.Format(".jpeg|*.jpeg|*.*|All Files");
//当前文件扩展名是否包含在这个字符串中
if (stringstrFileTypeLimit.IndexOf(fileName.ToLower()) != -)
{
return true;
}
else
{
return false;
}
} //文件大小
public bool IsAllowableFileSize(long FileContentLength)
{
//从web.config读取判断文件大小的限制
Int32 doubleiFileSizeLimit = ; //判断文件是否超出了限制
if (doubleiFileSizeLimit > FileContentLength)
{
return true;
}
else
{
return false;
}
} }
}
FTP上传文件夹的更多相关文章
- shell中利用ftp 上传文件夹功能
我们知道ftp 只能用来上传或者下载文件,一次单个或者多个,怎么实现将文件夹的上传和下载呢? 可以利用先在remote ip上建立一个相同的文件夹目录,然后将文件放到各自的目录中去 1.循环遍历出要上 ...
- FTP上传文件到服务器
一.初始化上传控件. 1.我们这里用dropzone.js作为上传控件,下载地址http://www.dropzonejs.com/ 2.这里我们使用一个div元素作为dropzone载体. < ...
- 再看ftp上传文件
前言 去年在项目中用到ftp上传文件,用FtpWebRequest和FtpWebResponse封装一个帮助类,这个在网上能找到很多,前台使用Uploadify控件,然后在服务器上搭建Ftp服务器,在 ...
- Ftp上传文件
package net.util.common; import java.io.File; import java.io.FileInputStream; import java.io.FileOut ...
- PHP使用FTP上传文件到服务器(实战篇)
我们在做开发的过程中,上传文件肯定是避免不了的,平常我们的程序和上传的文件都在一个服务器上,我们也可以使用第三方sdk上传文件,但是文件在第三方服务器上.现在我们使用PHP的ftp功能把文件上传到我们 ...
- java上传文件夹文件
这里只写后端的代码,基本的思想就是,前端将文件分片,然后每次访问上传接口的时候,向后端传入参数:当前为第几块文件,和分片总数 下面直接贴代码吧,一些难懂的我大部分都加上注释了: 上传文件实体类: 看得 ...
- java实现上传文件夹
我们平时经常做的是上传文件,上传文件夹与上传文件类似,但也有一些不同之处,这次做了上传文件夹就记录下以备后用. 首先我们需要了解的是上传文件三要素: 1.表单提交方式:post (get方式提交有大小 ...
- java+struts上传文件夹文件
这里只写后端的代码,基本的思想就是,前端将文件分片,然后每次访问上传接口的时候,向后端传入参数:当前为第几块文件,和分片总数 下面直接贴代码吧,一些难懂的我大部分都加上注释了: 上传文件实体类: 看得 ...
- .net FTP上传文件
FTP上传文件代码实现: private void UploadFileByWebClient() { WebClient webClient = new WebClient(); webClient ...
随机推荐
- linux下的mysql乱码问题
1,承接上一随笔,因为我用的是rmp的两种反式. rpm -ivh MySQL-server-4.0.14-0.i386.rpm rpm -ivh MySQL-client-4.0.14-0.i386 ...
- wcscpy wcscpy_s strcpy strcpy_s的区别
原型声明:extern char *strcpy(char *dest,const char *src); 头文件:string.h 功能:把从src地址开始且含有NULL结束符的字符串赋值到以des ...
- WP8__从windowsphone app store 中根据app id获取应用的相关信息(下载网址及图片id等)
windows phone 官网应用商店地址 http://www.windowsphone.com/zh-cn/store/featured-apps------------------------ ...
- 2016.04.09 使用Powerdesigner进行创建数据库的概念模型并转为物理模型
2016-04-09 21:10:24 本文原创受版权保护,严禁转载. 请大家不要用于商业用途,支持正版,大家都是做软件的,知道开发一套软件实属不易啊! 今天看到了一个很有趣并且很有用的辅助 ...
- poj1001_Exponentiation
这题真是超级大模拟.好繁琐,自己写的打数加法,乘法,写的比我大一时候写的要好很多,大一是借助C++里面的string来写的,这把只用了C,浇一次就ac了,挺开心的,不过写了2个小时啊.注意零的处理.大 ...
- idea类似eclipse鼠标提示java api信息
<ignore_js_op> 详细说明:http://java.662p.com/thread-2615-1-1.html
- iOS 层层推进实现代理模式
1.代理模式核心思想:A类委托B类做某件事,然后A类获取B类的执行的返回结果! 举例:女孩想去买电影票,但是自己不亲自去而是委托男孩了解电影电影票信息,同时女孩获得男孩买票的结果,代码模拟实现: /* ...
- .NET中 使用数组的注意事项
1.初始值问题 对于int.double.float等一些值类型数组,没有赋值的情况下, 默认值是0: 而对于String 等引用类型,初始值为null. 2.IndexOutOfRangeExcep ...
- JS日期(Date)处理函数总结
获取日期 1.Date() ——返回当日的日期和时间. 2.getDate() ——从 Date 对象返回一个月中的某一天 (1 ~ 31). 3.getDay() ——从 Date 对象返回一周中的 ...
- 转:OpenCms 9.0.1汉化
LHD私人汉化. 1.完成安装OpenCms 2.如果正确安装,在浏览器输入以下地址即可打开登录页面(默认账号/密码:Admin/admin) http://localhost:8080/opencm ...