工作中项目一直使用的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. Django 组件-中间件

    中间件 中间件的概念 中间件顾名思义,是介于request与response处理之间的一道处理过程,相对比较轻量级,并且在全局上改变django的输入与输出.因为改变的是全局,所以需要谨慎实用,用不好 ...

  2. Charles修改返回值的方法(构造返回值最大值的情况,比如100,99) (自己没有试过)

    第一步:save respond到电脑 第二步:打开文件,修改相应的参数 第三步:导入修改后的文件 第四步:手机刷新数据,查看结果

  3. CentOS7 php7 安装 curl 扩展

    直接从php源码包中,使用root权限安装. 找到原先安装PHP的源码包文件(如果已经删掉需要重新下载原来版本的源码包并解压) 我的php源码包在root家目录下. cd /php-7.1.4/ext ...

  4. [转]Jsp 映射

    <servlet> <servlet-name>SimpleJspServlet</servlet-name> <jsp-file>/jsp/simpl ...

  5. Log4j配置详解之log4j.xml

    Log4j配置详解之log4j.xml Log4J的配置文件(Configuration File)就是用来设置记录器的级别.存放器和布局的,它可接key=value格式的设置或xml格式的设置信息. ...

  6. css选择器30种

    CSS 选择器是一种模式,用于选择需要添加样式的元素.平时使用最多也是最简单的就是 #id..class 和标签选择器,在 CSS 中还有很多更加强大更加灵活的选择方式,尤其是在 CSS3 中,增加了 ...

  7. Window性能监视器

    Microsoft Web Application Stress Tool 微软的分布式网站性能压力测试工具 Window性能监视器 1.监测IIS连接数量 从“开始”菜单上选择“运行”. 在“打开” ...

  8. Linux的bond模式绑定及模式区别

    [Linux的bond模式配置] 原理: 多块网卡虚拟成一张,实现冗余:多张网卡对外显示一张,具有同一个IP: 工作在网卡是混杂模式的情况下: 对于多物理网卡的 Bond 网卡而言,其中一块物理网卡会 ...

  9. [ Python ] Flask 基于 Web开发 大型程序的结构实例解析

    作为一个编程入门新手,Flask是我接触到的第一个Web框架.想要深入学习,就从<FlaskWeb开发:基于Python的Web应用开发实战>这本书入手,本书由于是翻译过来的中文版,理解起 ...

  10. 深入浅出 Java Concurrency (12): 锁机制 part 7 信号量(Semaphore)

      Semaphore 是一个计数信号量.从概念上讲,信号量维护了一个许可集.如有必要,在许可可用前会阻塞每一个 acquire(),然后再获取该许可.每个 release() 添加一个许可,从而可能 ...