public class Path_File
{
public string AppPath
{
get
{
return AppDomain.CurrentDomain.BaseDirectory;
}
} public Path_File()
{ } /// <summary>
/// 查找指定路径下的文件夹
/// </summary>
/// <param name="parentDirPath">指定路径</param>
/// <param name="findDir">文件夹</param>
/// <param name="findDirPath">文件夹路径</param>
/// <returns>是否找到</returns>
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(, count);
isFind = true;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return isFind;
} /// <summary>
/// 获取指定目录下的子目录名集
/// </summary>
/// <param name="parentDirPath">指定目录</param>
/// <returns>子目录名集</returns>
public List<string> getChildDirectories(string parentDirPath,bool isFullName = false)
{
List<string> listDirs = new List<string>();
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;
} /// <summary>
/// 获取指定目录下的子文件名集
/// </summary>
/// <param name="parentDirPath">指定目录</param>
/// <returns>子目录名集</returns>
public List<string> getChildFiles(string parentDirPath, bool isFullName = false)
{
List<string> listFiles = new List<string>();
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;
} /// <summary>
/// 复制文件夹
/// </summary>
/// <param name="sourcePath">源目录</param>
/// <param name="targetPath">目的目录</param>
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;
} /// <summary>
/// 确认路径存在(不存在则创建路径)
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
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;
} /// <summary>
/// 删除指定文件
/// </summary>
/// <param name="fFullName"></param>
/// <returns></returns>
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;
} /// <summary>
/// 删除指定文件夹
/// </summary>
/// <param name="folderPath"></param>
/// <returns></returns>
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;
} /// <summary>
/// 替换路径下文件名中的标识
/// </summary>
/// <param name="filePath"></param>
/// <param name="oldTag"></param>
/// <param name="newTag"></param>
/// <returns></returns>
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;
} /// <summary>
/// 更级名称
/// </summary>
/// <param name="fileFullName"></param>
/// <param name="i"></param>
/// <returns></returns>
public string getUniqueName(string fileFullName, int i = )
{
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(, 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;
} /// <summary>
/// 更级名称
/// </summary>
/// <param name="fileFullName"></param>
/// <param name="i"></param>
/// <returns></returns>
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<string, string> 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;
} }

+ 去掉.

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

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

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

+过滤特殊字符

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

+打开文件夹浏览器

        /// <summary>
/// 打开文件夹浏览器
/// </summary>
/// <param name="dirPath"></param>
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;
}

+批量修改文件名

        /// <summary>
/// 修改文件名
/// </summary>
/// <param name="baseDirPath">基路径</param>
/// <param name="partName">修改文件名</param>
/// <param name="changeType">类型(0:替换,1:+前面,2:+后面)</param>
/// <param name="isRecursion">是递归</param>
/// <returns></returns>
public bool ChangeFilesName(string baseDirPath, string partName, int changeType, bool isRecursion)
{
bool isSuccess = true;
try
{
this.ConfirmPathExist(baseDirPath);
List<string> fileNames = this.getChildFiles(baseDirPath);
switch(changeType)
{
case :
int i = ;
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 :
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 :
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<string> dirFullNames = getChildDirectories(baseDirPath, true);
foreach(string dirFullName in dirFullNames)
{
ChangeFilesName(dirFullName, partName, changeType, isRecursion);
}
}
}
catch (Exception ex)
{
isSuccess = false;
}
return isSuccess;
}

+删除、清空目录

        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);
} /// <summary>
/// 清空目录
/// </summary>
/// <param name="path">目录全路径</param>
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);
}
}
}

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

C#:文件、路径(Path_File)的更多相关文章

  1. Oracle数据库文件路径变更

    环境:RHEL 6.4 + Oracle 11.2.0.3 情景一:只是部分普通数据文件迁移,可以在线操作. 1.将对应表空间offline,移动数据文件到新路径 2.数据文件alter databa ...

  2. Excel公式 提取文件路径后缀

    我们在代码中获取一个文件路径的后缀,是一个很简单的事. 如C#中,可以通过new FileInfo(filePath).Extension,或者Path.GetExtension(filePath)获 ...

  3. IISExpress Log 文件路径

    问题 用VS做开发时经常用IISExpress测试web程序,那么在测试过程中生成的Log文件放在哪里了? 答案 情况1 默认情况下 applicationhost.config 文中定义了连个日志文 ...

  4. [LeetCode] Longest Absolute File Path 最长的绝对文件路径

    Suppose we abstract our file system by a string in the following manner: The string "dir\n\tsub ...

  5. 使用powershell批量添加Keil和IAR的头文件路径

    在Keil和IAR的工程中,为了使文件结构清晰,通常会设置很多的子文件夹,然后将头文件和源文件放在不同的子文件夹中,这样就需要手动添加这些头文件夹的路径.当工程结构非常复杂时,文件夹的数量就非常多,特 ...

  6. Yii2:避免文件路径暴漏,代理访问文件

    制作背景:公司要做第三方文件管理系统,客户有时候需要直接访问文件,但是我们又不想暴露文件路径,才有这代理访问 基本功能介绍:读取txt文档.读取图片,如果有需要,可以通过插件读取doc.pdf文档, ...

  7. php glob()函数实现目录文件遍历与寻找与模式匹配的文件路径

    采用PHP函数glob实现寻找与模式匹配的文件路径,主要讨论glob()函数的作用和用法,利用glob函数读取目录比其它的要快N倍,因为glob函数是内置函数处理起来自然要快. 一,函数原型 arra ...

  8. java 读文件路径问题

    文件路径:右键点击src新建Source Folder,创建结果与src目录同级. C:\Users\lenovo\workspace\timedTask\config\userinfo.proper ...

  9. 关于获取web应用的文件路径的注意事项

    今天在把数据写入文件时遇到了一个问题,指定的文件获取不到.一开始是这样的 URL url = XXX.class.getClassLoader().getResource(fileName);File ...

  10. java通过文件路径读取该路径下的所有文件并将其放入list中

    java通过文件路径读取该路径下的所有文件并将其放入list中   java中可以通过递归的方式获取指定路径下的所有文件并将其放入List集合中.假设指定路径为path,目标集合为fileList,遍 ...

随机推荐

  1. Virtual Box 增加虚拟硬盘容量

    情景: 我现在用 Win10, 因为项目原因要在虚拟机装一个 Win7. 预先估计不足. Win7 C盘容量不够. 方法1: 增加虚拟硬盘文件. 首先把虚拟机 Win7 删掉 (但不要删虚拟硬盘文件, ...

  2. D3D9 GPU Hacks (转载)

    D3D9 GPU Hacks I’ve been trying to catch up what hacks GPU vendors have exposed in Direct3D9, and tu ...

  3. Oracle RAC 11.2.0.4 – RHRL 6.4: DiskGroup resource are not running on nodes. Database instance may not come up on these nodes

    使用DBCA创建新库的时候报错: 查看资源状态: $ crsctl stat res -t ------------------------------------------------------ ...

  4. docker summary

    http://blog.tankywoo.com/docker/2014/05/08/docker-4-summary.html 总结的很好 ----------------------------- ...

  5. Java基础之集合框架——使用真的的链表LinkedList<>(TryPolyLine)

    控制台程序. public class Point { // Create a point from its coordinates public Point(double xVal, double ...

  6. ViewController添加子控制器 并且弹出

    /** *  初始化子控制器 */ - (void)setupChildVcs { for (int i = 0; i<6; i++) { UIViewController *vc = [[UI ...

  7. Swift动画编程指南-02 Swift动画是怎么炼成的

    上一节我们看了几个很棒的例子,我们不禁会想.他们是怎么设计的,怎么从一个空白的画布变成一个完整的,美丽的动画.这些动画是如何产生的,是哪些属性被改变了.我们还要认真思考的是,每一个步骤到底发生了什么. ...

  8. 开篇呀,恭喜恭喜,是个好开头-----关于sort()排序

    感觉自己活了半辈子从来没写过博客,这可是头一回,而且不是记事是为了学习,先恭喜恭喜自己,有一个很好的开端,不管能不能半途而废,反正是想着为了学习做点什么. 之前有很多东西需要搬过来,循序渐进吧,反正也 ...

  9. 【Origin】答友朋关切书

    发烧感冒脑袋疼, 剃了短毛不威风: 莫再问我有何事, 躺下一觉到天明. --作于二零一五年七月二十七日

  10. bzoj4547 小奇的集合

    当序列中最大和次大都是负数的时候,其相加会是一个更小的负数,因此答案为(Σai)+(m1+m2)*k,如果最大是正数次大是负数,那么一直相加直到两个数都为正数,当最大和次大都是正数时,做一下矩阵乘法即 ...