工作中项目一直使用的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. 基于Video4Linux的视频采集模块开发(转)

    Linux系统中,摄像头驱动程序安装好后,为了进行视频采集必须加入Video4Linux模块,从而可以通过Video4Linux模块提供的编程接口(API)从摄像头设备中获取图像帧.下面具体研究基于V ...

  2. 使用JDK合成照片

    原图(工程所在目录7098849.jpg): 头像(工程所在目录20181023201750.jpg): 开始合成(执行如下main方法): public static void main(Strin ...

  3. Spring集成缓存

    Want 上一篇简单服务端缓存API设计设计并实现了一套缓存API,适应不同的缓存产品,本文重点是基于Spring框架集成应用开发. 缓存集成 以普通Web应用开发常见的搭配Spring+Spring ...

  4. bzoj1729: [Usaco2005 dec]Cow Patterns 牛的模式匹配

    Description     约翰的N(1≤N≤100000)只奶牛中出现了K(1≤K≤25000)只爱惹麻烦的坏蛋.奶牛们按一定的顺序排队的时候,这些坏蛋总会站在一起.为了找出这些坏蛋,约翰让他的 ...

  5. 让输入的字符转义成html实体的方法

    使用 htmlspecialchars() 函数,代码不会执行,因为会被保存为转义代码 总结测试方法: https://www.cnblogs.com/kaibindirver/p/10321448. ...

  6. nginx限制请求之一:(ngx_http_limit_conn_module)模块

    相关文章: <高可用服务设计之二:Rate limiting 限流与降级> <nginx限制请求之一:(ngx_http_limit_conn_module)模块> <n ...

  7. nginx限制请求之二:(ngx_http_limit_req_module)模块

    相关文章: <高可用服务设计之二:Rate limiting 限流与降级> <nginx限制请求之一:(ngx_http_limit_conn_module)模块> <n ...

  8. hdu 1576 A/B(拓展欧几里得)

    A/B Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submiss ...

  9. 1123 Is It a Complete AVL Tree

    1123 Is It a Complete AVL Tree(30 分) An AVL tree is a self-balancing binary search tree. In an AVL t ...

  10. UE4 代码总结

    1.创建关卡类 1.创建C++类继承LevelScriptActor 2.打开关卡蓝图 Class Settings->Parent Class 选择你之前创建好的C++类 遇到的问题: 1.T ...