工作中项目一直使用的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. Bootstrap树控件(Tree控件组件)使用经验分享

    前言:很多时候我们在项目中需要用到树,有些树仅仅是展示层级关系,有些树是为了展示和编辑层级关系,还有些树是为了选中项然后其他地方调用选中项.不管怎么样,树控件都是很多项目里面不可或缺的组件之一.今天, ...

  2. bzoj 1101 [POI2007]Zap——反演

    题目:https://www.lydsy.com/JudgeOnline/problem.php?id=1101 #include<cstdio> #include<cstring& ...

  3. ESP8266编译过程探索

    首先看到的是为什么SDK里有一个libmain.a这样的库. 编译之后才发现原平是这样子:main函数(如果有的话)会调用我们user_init函数.user_rf_cal_sector_set函数, ...

  4. 黄聪:免费C#反编译软件工具。Reflector已经out了,试试ILSpy吧

    转载自:http://www.cnblogs.com/JamesLi2015/archive/2011/09/08/2170519.html Reflector是.NET开发中必备的反编译工具.即使没 ...

  5. C#操作MySql数据库帮助类(Dapper,T-Sql)

    using System.Text; using MySql.Data.MySqlClient; using System.Data; using Dapper; using System.Refle ...

  6. 让html标签显示在页面上

    用 <xmp></xmp> 标签包起来,里面的所有文字会原样显示出来 <xmp><b>1</b><div>2</div&g ...

  7. Echarts运用

    echarts客户端写法:http://echarts.baidu.com/doc/example.html  ,下载echarts-2.0.4.jar包,把src里面的js引入到项目里,在放esl. ...

  8. [C++]复制构造函数、赋值操作符与隐式类类型转换

    问题:现有类A定义如下: class A{public:        A(int a)                            //构造函数        {              ...

  9. Linux学习笔记 -- stdin/stdout 重定向

    输入/输出重定向 Linux系统通常从一个叫标准输入的地方读取输入并且将一个命令的结果以写入到标准输出反馈给我们:默认情况下,这也是我们使用的终端(命令行).如果我们想改变输入和输出的方式,就需要使用 ...

  10. 缓存varnish的管理及配置详解

    一 工作原理 在当前主流的Web服务架构体系中,Cache担任着越来越重要的作用.常见的基于浏览器的C/S架构,Web Cache更是节约服务器资源的关键.而最近几年由FreeBSD创始人之一Kamp ...