WEB开发网
开发学院WEB开发ASP.NET C# .NET FTP上传文件夹操作 阅读

C# .NET FTP上传文件夹操作

 2012-03-28 09:28:21 来源:WEB开发网   
核心提示:#region 上传文件夹/// <summary>/// 获取目录下的详细信息/// </summary>/// <param name="localDir">本机目录</param>/// <returns></returns&g
#region 上传文件夹
/// <summary>
/// 获取目录下的详细信息
/// </summary>
/// <param name="localDir">本机目录</param>
/// <returns></returns>
private static 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 = 0; i < infos[0].Count; i++)
{
int index = infos[0][i].LastIndexOf(@"\");
infos[0][i] = infos[0][i].Substring(index + 1);
}
for (int i = 0; i < infos[1].Count; i++)
{
int index = infos[1][i].LastIndexOf(@"\");
infos[1][i] = infos[1][i].Substring(index + 1);
}
}
catch (Exception ex)
{
ex.ToString();
}
return infos;
}
/// <summary>
/// 上传整个目录
/// </summary>
/// <param name="localDir">要上传的目录的上一级目录</param>
/// <param name="ftpPath">FTP路径</param>
/// <param name="dirName">要上传的目录名</param>
/// <param name="ftpUser">FTP用户名(匿名为空)</param>
/// <param name="ftpPassword">FTP登录密码(匿名为空)</param>
public static 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))
{
MyLog.ShowMessage("目录:“" + 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 = 0; i < infos[0].Count; i++)
{
Console.WriteLine(infos[0][i]);
UpLoadFile(dir + infos[0][i], ftpPath + dirName + @"/" + infos[0][i], ftpUser, ftpPassword);
}
//再处理文件夹
MyLog.ShowMessage(dir + "下的目录数:" + infos[1].Count.ToString());
for (int i = 0; i < infos[1].Count; i++)
{
UploadDirectory(dir, ftpPath + dirName + @"/", infos[1][i], ftpUser, ftpPassword);
}
}

调用:

//FTP地址
string ftpPath = @"Ftp://192.168.1.68:21/";
//本机要上传的目录的父目录
string localPath = @"D:\";
//要上传的目录名
string fileName = @"haha";
FTPClient.UploadDirectory(localPath, ftpPath, fileName, "", "");

Tags:NET FTP 上传

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接