工作中项目一直使用的ftp上传日志文件出现了问题,新的服务器搭建好后,日志无法上传。正好来学习一下ftp。

程序中的流程是,一个计时器,每分钟检测配置文件中本地日志文件路径下有没有日志文件,如果有就上传到服务器上去,然后把本地的文件删掉。日志以日期为单位,每天一个文件夹,之后是日志类型,按类型分文件夹。上传之前先检测服务器上是否存在该文件夹,如果不存在则创建一个文件。

下面是代码。(只放ftp那部分)

/// <summary>
/// 判断文件的目录是否存,不存则创建
/// </summary>
/// <param name="destFilePath">本地文件目录</param>
public void CheckDirectoryAndMakeMyWilson3(string destFilePath)
{
string fullDir = destFilePath.IndexOf(':') > ? destFilePath.Substring(destFilePath.IndexOf(':') + ) : destFilePath;
fullDir = fullDir.Replace('\\', '/');
string[] dirs = fullDir.Split('/');//解析出路径上所有的文件名
string curDir = "/";
for (int i = ; i < dirs.Length; i++)//循环查询每一个文件夹
{
if (dirs[i] == "") continue;
string dir = dirs[i];
//如果是以/开始的路径,第一个为空
if (dir != null && dir.Length > )
{
try
{ CheckDirectoryAndMakeMyWilson2(curDir, dir);
curDir += dir + "/";
}
catch (Exception)
{ }
}
}
}
public void CheckDirectoryAndMakeMyWilson2(string rootDir, string remoteDirName)
{
if (!DirectoryExist(rootDir, remoteDirName))//判断当前目录下子目录是否存在
MakeDir(rootDir + "\\" + remoteDirName);
}
/// <summary>
/// 判断当前目录下指定的子目录是否存在
/// </summary>
/// <param name="RemoteDirectoryName">指定的目录名</param>
public bool DirectoryExist(string rootDir, string RemoteDirectoryName)
{
string[] dirList = GetDirectoryList(rootDir);//获取子目录
if (dirList.Length > )
{
foreach (string str in dirList)
{
if (str.Trim() == RemoteDirectoryName.Trim())
{
return true;
}
}
}
return false;
}
//获取子目录
public string[] GetDirectoryList(string dirName)
{
string[] drectory = GetFilesDetailList(dirName);
List<string> strList = new List<string>();
if (drectory.Length > )
{
foreach (string str in drectory)
{
if (str.Trim().Length == )
continue;
//会有两种格式的详细信息返回
//一种包含<DIR>
//一种第一个字符串是drwxerwxx这样的权限操作符号
//现在写代码包容两种格式的字符串
if (str.Trim().Contains("<DIR>"))
{
strList.Add(str.Substring().Trim());
}
else
{
if (str.Trim().Substring(, ).ToUpper() == "D")
{
strList.Add(str.Substring().Trim());
}
}
}
}
return strList.ToArray();
}
/// <summary>
/// 获得文件明晰
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public string[] GetFilesDetailList(string path)
{
return GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectoryDetails);
}
//都调用这个
//上面的代码示例了如何从ftp服务器上获得文件列表
private string[] GetFileList(string path, string WRMethods)
{
StringBuilder result = new StringBuilder();
try
{
Connect(path);//建立FTP连接
reqFTP.Method = WRMethods;
reqFTP.KeepAlive = false;
WebResponse response = reqFTP.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);//中文文件名
string line = reader.ReadLine(); while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
} // to remove the trailing '' ''
if (result.ToString() != "")
{
result.Remove(result.ToString().LastIndexOf("\n"), );
}
reader.Close();
response.Close();
return result.ToString().Split('\n');
} catch (Exception ex)
{
throw new Exception("获取文件列表失败。原因: " + ex.Message);
}
}
//连接ftp
private void Connect(String path)
{
// 根据uri创建FtpWebRequest对象
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
// 指定数据传输类型
reqFTP.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
reqFTP.UseBinary = true;
reqFTP.UsePassive = false;//表示连接类型为主动模式
// ftp用户名和密码
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
}
/// <summary>
/// 创建目录
/// </summary>
/// <param name="dirName"></param>
public void MakeDir(string dirName)
{
try
{
string uri = "ftp://" + ftpServerIP + "/" + dirName;
Connect(uri);//连接
reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
reqFTP.KeepAlive = false;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
response.Close();
} catch (Exception ex)
{
throw new Exception("创建文件失败,原因: " + ex.Message);
} }

c# ftp 判断目录是否存在和创建文件夹的更多相关文章

  1. Java创建文件夹、创建文件、上传文件,下载文件

    1.创建文件夹 /** * 判断文件夹是否存在 * @param myPath */ public static void judeDirExists(File myPath) { if (!myPa ...

  2. PHP判断文件夹是否存在和创建文件夹的方法(递归创建多级目录)

    在开始之前,我先说明一下,可能许多朋友与我一样认为只要给一个路径,mkdir就可以创建文件夹,其实不是那样,单个的MKDIR只能创建一级目录,对于多级的就不行了,那如何用mkdir来创建呢?先我抄一段 ...

  3. Java 判断文件夹、文件是否存在、否则创建文件夹

    1.判断文件是否存在,不存在创建文件 File file=new File("C:\\Users\\QPING\\Desktop\\JavaScript\\2.htm"); if( ...

  4. 判断文件是否存在,不存在创建文件&&判断文件夹是否存在,不存在创建文件夹

    1.判断文件是否存在,不存在创建文件 File file=new File("C:\\Users\\QPING\\Desktop\\JavaScript\\2.htm"); if( ...

  5. JAVA之旅(二十八)——File概述,创建,删除,判断文件存在,创建文件夹,判断是否为文件/文件夹,获取信息,文件列表,文件过滤

    JAVA之旅(二十八)--File概述,创建,删除,判断文件存在,创建文件夹,判断是否为文件/文件夹,获取信息,文件列表,文件过滤 我们可以继续了,今天说下File 一.File概述 文件的操作是非常 ...

  6. Python3 判断文件和文件夹是否存在、创建文件夹

    Python3 判断文件和文件夹是否存在.创建文件夹 python中对文件.文件夹的操作需要涉及到os模块和shutil模块. 创建文件: 1) os.mknod(“test.txt”) 创建空文件  ...

  7. 【每天一个Linux命令】19. 创建文件夹目录命令mkdir

    命令用途 mkdir 命令用来创建指定的名称的目录 使用说明 1.  创建目录的用户在当前目录中具有写权限 2. 指定的目录名不能是当前目录中已有的目录. 命令实例 0. 帮助文件 bixiaopen ...

  8. mac home目录创建文件夹,修改权限

    mac 是基于unix, 自带就有home目录,但是为空.home目录的默认所属用户是root wheel,mac默认的root账号所属用户是root admin,所以root也无法在home目录下创 ...

  9. Inno Setup入门(六)——在程序目录下创建文件夹

    创建文件夹可以使用[dirs]段实现,代码如下: [setup] ;全局设置,本段必须 AppName=Test AppVerName=TEST DefaultDirName="E:\TES ...

随机推荐

  1. 学习 Git 玩转 GitHub

    原文地址:学习 Git 玩转 GitHub 博客地址:http://www.extlight.com 一.基本了解 1.1 什么是版本控制系统 版本控制系统是一种记录一个或若干个文件内容变化,以便将来 ...

  2. WiresShark使用说明

    WiresShark是号称全世界最流行的网络分析工具(它的官网自己说的).下载地址:https://www.wireshark.org/#download,目前最新版本是2.6.2.我本地用的是汉化的 ...

  3. golang的beego框架开发时出现的问题纪录

    golang的beego框架开发时出现的问题纪录1.数据库并发时问题:[ORM]2017/02/20 23:44:05 -[Queries/default] - [FAIL / db.Query / ...

  4. ora-01658: 无法为表空间*****中的段创建 INITIAL 区

    ora-01658: 无法为表空间*****中的段创建 INITIAL 区 原因:表空间不足 增大表空间.如果表空间动态增长,则扩大表空间的最大值.

  5. bean对grub4dos做出的巨大贡献总结

    bean对grub4dos做出的巨大贡献总结 ===================================================================bean对grub4 ...

  6. python查找字符串 函数find() 用法

    sStr1 = 'abcdefg' sStr2 = 'cde' print sStr1.find(sStr2) 输出 2意思是在sStr1字符里的第2位置找到了包含cde字符的字段

  7. [Java][Web]解决 Request 的乱码

    解决 get 提交的乱码 (手工处理) String username = request.getParameter("username"); username = new Str ...

  8. python学习(二十三) String(下) 分片和索引

    分片: 记住, 是开闭区间. a = "abcdef"print(a[:])print(a[1:])print(a[:3])print(a[-2])print(a[:-2])pri ...

  9. 什么是java序列化,如何实现java序列化?

    http://veryti.com/question/539 序列化就是一种用来处理对象流的机制,所谓对象流也就是将对象的内容进行流化.可以对流化后的对象进行读写操作,也可将流化后的对象传输于网络之间 ...

  10. wget 技巧

    最近用到一个命令wget,有一个技巧分享一下. [root@py ~]# wget -m -k http://www.example.com 可以将示例网站整个打包,作为本地镜像.