網站首頁 編程語言 正文
C# ftp判斷目錄是否存在,不存在則自動創建文件夾
/// <summary>
/// 判斷文件的目錄是否存,不存則創建
/// </summary>
/// <param name="destFilePath">本地文件目錄</param>
public void CheckDirectoryAndMakeMyWilson3(string destFilePath)
{
string fullDir = destFilePath.IndexOf(':') > 0 ? destFilePath.Substring(destFilePath.IndexOf(':') + 1) : destFilePath;
fullDir = fullDir.Replace('\\', '/');
string[] dirs = fullDir.Split('/');//解析出路徑上所有的文件名
string curDir = "/";
for (int i = 0; i < dirs.Length; i++)//循環查詢每一個文件夾
{
if (dirs[i] == "") continue;
string dir = dirs[i];
//如果是以/開始的路徑,第一個為空
if (dir != null && dir.Length > 0)
{
try
{
CheckDirectoryAndMakeMyWilson2(curDir, dir);
curDir += dir + "/";
}
catch (Exception)
{ }
}
}
}
public void CheckDirectoryAndMakeMyWilson2(string rootDir, string remoteDirName)
{
if (!DirectoryExist(rootDir, remoteDirName))//判斷當前目錄下子目錄是否存在
MakeDir(rootDir + "\\" + remoteDirName);
}
public bool DirectoryExist(string rootDir, string RemoteDirectoryName)
{
string[] dirList = GetDirectoryList(rootDir);//獲取子目錄
if (dirList.Length > 0)
{
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 > 0)
{
foreach (string str in drectory)
{
if (str.Trim().Length == 0)
continue;
//會有兩種格式的詳細信息返回
//一種包含<DIR>
//一種第一個字符串是drwxerwxx這樣的權限操作符號
//現在寫代碼包容兩種格式的字符串
if (str.Trim().Contains("<DIR>"))
{
strList.Add(str.Substring(39).Trim());
}
else
{
if (str.Trim().Substring(0, 1).ToUpper() == "D")
{
strList.Add(str.Substring(55).Trim());
}
}
}
}
return strList.ToArray();
}
定義ftp地址:private string ftpServerIP = "IP:端口";
/// <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"), 1);
}
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);
}
}
原文鏈接:https://blog.csdn.net/qq_37192571/article/details/125555625
相關推薦
- 2022-05-26 .Net解決引用程序集沒有強名稱報錯_實用技巧
- 2023-01-28 Python進程間通訊與進程池超詳細講解_python
- 2022-08-10 Go語言pointer及switch?fallthrough實戰詳解_Golang
- 2022-07-19 提升Python運算效率1 - numba-jit
- 2022-07-09 利用go語言實現查找二叉樹中的最大寬度_Golang
- 2022-08-26 Python中CSV文件(逗號分割)實戰操作指南_python
- 2022-03-06 C#中List用法介紹詳解_C#教程
- 2024-01-16 ignore_above 解決keyword字段超長
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支