博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#:文件、路径(Path_File)
阅读量:6072 次
发布时间:2019-06-20

本文共 14665 字,大约阅读时间需要 48 分钟。

public class Path_File    {        public string AppPath        {            get            {                return AppDomain.CurrentDomain.BaseDirectory;            }        }        public Path_File()        {                   }        ///         /// 查找指定路径下的文件夹        ///         /// 指定路径        /// 文件夹        /// 文件夹路径        /// 
是否找到
public bool FindDirectory(string parentDirPath, string findDir, ref string findDirPath, bool isRecursion = true) { bool isFind = false; try { DirectoryInfo folder = new DirectoryInfo(parentDirPath.Trim()); //指定搜索文件夹 if (folder.Exists && !parentDirPath.Contains(findDir))//存在 文件夹 { DirectoryInfo[] listDirInfos = folder.GetDirectories();//取得给定文件夹下的文件夹组 if (listDirInfos != null) { foreach (DirectoryInfo dirInfo in listDirInfos)//遍历 { if (dirInfo.Name.ToLower() == findDir.Trim().ToLower()) { findDirPath = dirInfo.FullName; isFind = true; break; } } if (!isFind && isRecursion) //目录内未找到切递归子目录查找 { foreach (DirectoryInfo dirInfo in listDirInfos)//遍历 { string newParentDirPath = Path.Combine(parentDirPath, dirInfo.Name); isFind = FindDirectory(newParentDirPath, findDir, ref findDirPath, isRecursion); if (isFind) { break; } } } } } else { int count = parentDirPath.LastIndexOf(findDir) + findDir.Length; findDirPath = parentDirPath.Substring(0, count); isFind = true; } } catch (Exception ex) { throw new Exception(ex.Message); } return isFind; } /// /// 获取指定目录下的子目录名集 /// /// 指定目录 ///
子目录名集
public List
getChildDirectories(string parentDirPath,bool isFullName = false) { List
listDirs = new List
(); DirectoryInfo folder = new DirectoryInfo(parentDirPath.Trim()); //指定搜索文件夹 if (folder.Exists)//存在 文件夹 { DirectoryInfo[] listDirInfos = folder.GetDirectories();//取得给定文件夹下的文件夹组 if (listDirs != null) { foreach (DirectoryInfo dirInfo in listDirInfos)//遍历 { if (isFullName) { listDirs.Add(dirInfo.FullName); } else { listDirs.Add(dirInfo.Name); } } } } return listDirs; } ///
/// 获取指定目录下的子文件名集 /// ///
指定目录 ///
子目录名集
public List
getChildFiles(string parentDirPath, bool isFullName = false) { List
listFiles = new List
(); DirectoryInfo folder = new DirectoryInfo(parentDirPath.Trim()); //指定搜索文件夹 if (folder.Exists)//存在 文件夹 { FileInfo[] listFileInfos = folder.GetFiles();//取得给定文件夹下的文件夹组 if (listFiles != null) { foreach (FileInfo fileInfo in listFileInfos)//遍历 { if (isFullName) { listFiles.Add(fileInfo.FullName); } else { listFiles.Add(fileInfo.Name); } } } } return listFiles; } ///
/// 复制文件夹 /// ///
源目录 ///
目的目录 public bool CopyFolder(string sourcePath, string targetPath) { bool isSuccess = true; try { DirectoryInfo sourceInfo = new DirectoryInfo(sourcePath); if (sourceInfo.Exists) //源目录存在 { DirectoryInfo targetInfo = new DirectoryInfo(targetPath); if (!targetInfo.Exists) { targetInfo.Create(); } FileInfo[] files = sourceInfo.GetFiles(); //拷贝文件 foreach (FileInfo file in files) { file.CopyTo(Path.Combine(targetPath, file.Name), true); } DirectoryInfo[] childDirInfos = sourceInfo.GetDirectories(); //拷贝目录 foreach (DirectoryInfo dirInfo in childDirInfos) { CopyFolder(Path.Combine(sourcePath, dirInfo.Name), Path.Combine(targetPath, dirInfo.Name)); } } } catch (Exception) { isSuccess = false; } return isSuccess; } ///
/// 确认路径存在(不存在则创建路径) /// ///
///
public bool ConfirmPathExist(string path) { bool isExist = true; try { DirectoryInfo folder = new DirectoryInfo(path.Trim()); if (!folder.Exists)//不存在 文件夹 { folder.Create(); } } catch(Exception ex) { isExist = false; } return isExist; } ///
/// 删除指定文件 /// ///
///
public bool DeleteFile(string fFullName) { bool isSuccess = true; try { FileInfo fInfo = new FileInfo(fFullName); if (fInfo.Exists)//存在 文件 { fInfo.Delete(); } } catch (Exception ex) { isSuccess = false; } return isSuccess; } ///
/// 删除指定文件夹 /// ///
///
public bool DeleteFolder(string folderPath) { bool isSuccess = true; try { DirectoryInfo dirInfo = new DirectoryInfo(folderPath); if (dirInfo.Exists)//存在 文件夹 { dirInfo.Delete(true); } } catch (Exception ex) { isSuccess = false; } return isSuccess; } ///
/// 替换路径下文件名中的标识 /// ///
///
///
///
public bool ReplaceTagFromName(string filePath, string oldTag, string newTag,bool isIgnorCase = false) { bool isSuccess = true; try { DirectoryInfo dirInfo = new DirectoryInfo(filePath); if (!dirInfo.Exists) { dirInfo.Create(); } FileInfo[] fileInfos = dirInfo.GetFiles(); foreach (FileInfo fileInfo in fileInfos) { string name = Path.GetFileNameWithoutExtension(fileInfo.Name); if (isIgnorCase) { name = name.ToLower(); oldTag = oldTag.ToLower(); } string newName = name.Replace(oldTag, newTag); string newFileName = newName + fileInfo.Extension; string fullName = Path.Combine(filePath,newFileName); fileInfo.MoveTo(fullName); } } catch (Exception ex) { isSuccess = false; } return isSuccess; } ///
/// 更级名称 /// ///
///
///
public string getUniqueName(string fileFullName, int i = 0) { string fileName = fileFullName; try { FileInfo fInfo = new FileInfo(fileFullName); if (fInfo.Exists) { string ext = fInfo.Extension; int length = fileFullName.LastIndexOf(ext); fileName = fInfo.FullName.Substring(0, length) + i + ext; //string fileNamePath = Path.GetDirectoryName(fileFullName); //string fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileFullName); //仅获取文件名,不包含路径 //fileName = fileNameWithoutExt + i + ext; //fileName = Path.Combine(fileNamePath,fileName); fInfo = new FileInfo(fileName); if (fInfo.Exists) { i++; fileName = getUniqueName(fileFullName, i); } } } catch { } return fileName; } ///
/// 更级名称 /// ///
///
///
public bool UpdateName(string fileFullName) { bool isSuccess = true; try { string newName = getUniqueName(fileFullName); FileInfo fInfo = new FileInfo(fileFullName); if (fInfo.Exists) { fInfo.MoveTo(newName); } } catch { isSuccess = false; } return isSuccess; } public bool SaveInfos(string fileFullName, Dictionary
booksInfo, string tag = "|") { bool isSuccess = true; try { FileInfo fInfo = new FileInfo(fileFullName); FileStream fStream = null; if (!fInfo.Exists) { fStream = fInfo.Create(); } else { fStream = fInfo.Open(FileMode.CreateNew,FileAccess.ReadWrite); } StreamWriter sWrite = new StreamWriter(fStream);//(fileFullName, true); foreach (string bookId in booksInfo.Keys) { string lineInfo = bookId + tag + booksInfo[bookId]; sWrite.WriteLine(lineInfo); sWrite.Flush(); } sWrite.Close(); } catch { isSuccess = false; } return isSuccess; } public bool AppendInfo(string fileFullName,string Info) { bool isSuccess = true; try { FileInfo fInfo = new FileInfo(fileFullName); FileStream fStream = null; if (!fInfo.Exists) { fStream = fInfo.Create(); } else { fStream = fInfo.Open(FileMode.Append, FileAccess.ReadWrite); } StreamWriter sWrite = new StreamWriter(fStream); sWrite.WriteLine(Info); sWrite.Flush(); sWrite.Close(); } catch { isSuccess = false; } return isSuccess; } }
View Code

 

+ 去掉.

  :string ext = Path.GetExtension(fileName.Trim()).Replace(".",string.Empty);

+文件名称是否包含标识字符串:

public bool isFileNameContainsFlags(string fileName,List
contentFlags) { bool isContain = false; if (contentFlags == null || contentFlags.Count == 0) { isContain = true; } else { foreach (string flag in contentFlags) { if (fileName.Contains(flag.Trim())) { isContain = true; break; } } } return isContain; }
View Code

 +过滤特殊字符

///         /// 过滤掉非法字符和点字符        ///         ///         /// 
public String DirectoryNameFilter(String directoryName) { string invalidChars = "\\/:*?\"<>|."; //自定义非法字符(比系统的多了个.) foreach (char c in invalidChars) { directoryName = directoryName.Replace(c.ToString(), string.Empty); } return directoryName; } /// /// 过滤掉非法字符 /// /// ///
public String NameFilter(String name) { string invalidChars = "\\/:*?\"<>|"; //自定义非法字符(比系统的多了个.) foreach (char c in invalidChars) { name = name.Replace(c.ToString(), string.Empty); } return name; }
View Code

 

+打开文件夹浏览器

///         /// 打开文件夹浏览器        ///         ///         private string ShowFolderDialog(string dirPath)        {            string forderPath = dirPath.Trim();            if (!string.IsNullOrEmpty(forderPath))            {                this.fld_dlg.SelectedPath = forderPath;            }            DialogResult dlgResult = fld_dlg.ShowDialog();            if (dlgResult == DialogResult.OK)            {                forderPath = fld_dlg.SelectedPath;            }            return forderPath;        }
View Code

 +批量修改文件名

///         /// 修改文件名        ///         /// 基路径        /// 修改文件名        /// 类型(0:替换,1:+前面,2:+后面)        /// 是递归        /// 
public bool ChangeFilesName(string baseDirPath, string partName, int changeType, bool isRecursion) { bool isSuccess = true; try { this.ConfirmPathExist(baseDirPath); List
fileNames = this.getChildFiles(baseDirPath); switch(changeType) { case 0: int i = 0; foreach(string fName in fileNames) { string srcFullName = Path.Combine(baseDirPath,fName); FileInfo fInfo = new FileInfo(srcFullName); string dstFileName = partName + i + Path.GetExtension(fName); string dstFullName = Path.Combine(baseDirPath, dstFileName); fInfo.MoveTo(dstFullName); i++; } break; case 1: foreach(string fName in fileNames) { string srcFullName = Path.Combine(baseDirPath,fName); FileInfo fInfo = new FileInfo(srcFullName); string dstFileName = partName + fName; string dstFullName = Path.Combine(baseDirPath, dstFileName); fInfo.MoveTo(dstFullName); } break; case 2: foreach (string fName in fileNames) { string srcFullName = Path.Combine(baseDirPath, fName); FileInfo fInfo = new FileInfo(srcFullName); string dstFileName = Path.GetFileNameWithoutExtension(fName) + partName + Path.GetExtension(fName); string dstFullName = Path.Combine(baseDirPath, dstFileName); fInfo.MoveTo(dstFullName); } break; default: break; } if (isRecursion) { List
dirFullNames = getChildDirectories(baseDirPath, true); foreach(string dirFullName in dirFullNames) { ChangeFilesName(dirFullName, partName, changeType, isRecursion); } } } catch (Exception ex) { isSuccess = false; } return isSuccess; }
View Code

 

 +删除、清空目录

private void DeleteDirector(string path)        {            if (!Directory.Exists(path))                return;            string[] subdir = Directory.GetDirectories(path);            foreach (string dir in subdir)                DeleteDirector(dir);            string[] files = Directory.GetFiles(path);            foreach (string file in files)            {                File.Delete(file);            }            Directory.Delete(path);        }        ///         /// 清空目录        ///         /// 目录全路径        private void ClearDirectory(string path)        {            if (!Directory.Exists(path))                return;            string[] files = Directory.GetFiles(path);            foreach (string file in files)            {                try                {                    File.Delete(file);                }                catch (Exception e)                {                    _logger.Info("删除文件失败: ", e);                }            }            string[] dirs = Directory.GetDirectories(path);            foreach (string dir in dirs)            {                try                {                    ClearDirectory(dir);                    Directory.Delete(dir);                }                catch (Exception e)                {                    _logger.Info("删除目录失败: ", e);                }            }        }
View Code

 

 

 

 

更多:http://www.cnblogs.com/shenchao/p/5431163.html

你可能感兴趣的文章
JPA + Hibernate + PostgreSQL + Maven基本配置示例
查看>>
vue cordova生成app
查看>>
Kubernetes安装部署演示介绍
查看>>
koa中间件
查看>>
form表单的默认提交行为
查看>>
BZOJ 4128 Matrix ——BSGS
查看>>
Math(初学)
查看>>
读书笔记之:鸟哥的Linux私房菜——基础学习篇(第三版) (13-17章)
查看>>
三位对我影响最大的老师
查看>>
一个gulp用于开发与生产的示例
查看>>
2015区域赛起航
查看>>
服务器电脑名称改后,需要修改那些内容。
查看>>
第186天:js深入理解构造函数和原型对象
查看>>
页面自动刷新
查看>>
职业规划
查看>>
ansible小结
查看>>
银联支付Java开发
查看>>
最小编辑距离
查看>>
++a和--a以及a++和a--
查看>>
ios--控件--自定义封装一个控件
查看>>