c# 文件及目录操作类
18位长度的计时周期数: DateTime.Now.Ticks.ToString()
多数是收集而来,加上测试感觉很不错,分享一下或许有些帮助吧:
引用:
- using System;
- using System.Text;
- using System.IO;
主代码:
- namespace PorjectTools
- {
- ///<summary>
- ///</summary>
- public static class FileHelper
- {
- #region 检测指定目录是否存在
- /// <summary>
- /// 检测指定目录是否存在
- /// </summary>
- /// <param name="directoryPath">目录的绝对路径</param>
- public static bool IsExistDirectory(string directoryPath)
- {
- return Directory.Exists(directoryPath);
- }
- #endregion
- #region 检测指定文件是否存在
- /// <summary>
- /// 检测指定文件是否存在,如果存在则返回true。
- /// </summary>
- /// <param name="filePath">文件的绝对路径</param>
- public static bool IsExistFile(string filePath)
- {
- return File.Exists(filePath);
- }
- #endregion
- #region 检测指定目录是否为空
- /// <summary>
- /// 检测指定目录是否为空
- /// </summary>
- /// <param name="directoryPath">指定目录的绝对路径</param>
- public static bool IsEmptyDirectory(string directoryPath)
- {
- try
- {
- //判断是否存在文件
- string[] fileNames = GetFileNames(directoryPath);
- if (fileNames.Length > 0)
- {
- return false;
- }
- //判断是否存在文件夹
- string[] directoryNames = GetDirectories(directoryPath);
- return directoryNames.Length <= 0;
- }
- catch
- {
- return false;
- }
- }
- #endregion
- #region 检测指定目录中是否存在指定的文件
- /// <summary>
- /// 检测指定目录中是否存在指定的文件,若要搜索子目录请使用重载方法.
- /// </summary>
- /// <param name="directoryPath">指定目录的绝对路径</param>
- /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
- /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>
- public static bool Contains(string directoryPath, string searchPattern)
- {
- try
- {
- //获取指定的文件列表
- string[] fileNames = GetFileNames(directoryPath, searchPattern, false);
- //判断指定文件是否存在
- return fileNames.Length != 0;
- }
- catch
- {
- return false;
- }
- }
- /// <summary>
- /// 检测指定目录中是否存在指定的文件
- /// </summary>
- /// <param name="directoryPath">指定目录的绝对路径</param>
- /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
- /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>
- /// <param name="isSearchChild">是否搜索子目录</param>
- public static bool Contains(string directoryPath, string searchPattern, bool isSearchChild)
- {
- try
- {
- //获取指定的文件列表
- string[] fileNames = GetFileNames(directoryPath, searchPattern, true);
- //判断指定文件是否存在
- return fileNames.Length != 0;
- }
- catch
- {
- return false;
- }
- }
- #endregion
- #region 创建一个目录
- /// <summary>
- /// 创建一个目录
- /// </summary>
- /// <param name="directoryPath">目录的绝对路径</param>
- public static void CreateDirectory(string directoryPath)
- {
- //如果目录不存在则创建该目录
- if (!IsExistDirectory(directoryPath))
- {
- Directory.CreateDirectory(directoryPath);
- }
- }
- #endregion
- #region 创建一个文件
- /// <summary>
- /// 创建一个文件。
- /// </summary>
- /// <param name="filePath">文件的绝对路径</param>
- public static bool CreateFile(string filePath)
- {
- try
- {
- //如果文件不存在则创建该文件
- if (!IsExistFile(filePath))
- {
- //创建一个FileInfo对象
- FileInfo file = new FileInfo(filePath);
- //创建文件
- FileStream fs = file.Create();
- //关闭文件流
- fs.Close();
- }
- }
- catch
- {
- return false;
- }
- return true;
- }
- /// <summary>
- /// 创建一个文件,并将字节流写入文件。
- /// </summary>
- /// <param name="filePath">文件的绝对路径</param>
- /// <param name="buffer">二进制流数据</param>
- public static bool CreateFile(string filePath, byte[] buffer)
- {
- try
- {
- //如果文件不存在则创建该文件
- if (!IsExistFile(filePath))
- {
- //创建一个FileInfo对象
- FileInfo file = new FileInfo(filePath);
- //创建文件
- FileStream fs = file.Create();
- //写入二进制流
- fs.Write(buffer, 0, buffer.Length);
- //关闭文件流
- fs.Close();
- }
- }
- catch
- {
- return false;
- }
- return true;
- }
- #endregion
- #region 获取文本文件的行数
- /// <summary>
- /// 获取文本文件的行数
- /// </summary>
- /// <param name="filePath">文件的绝对路径</param>
- public static int GetLineCount(string filePath)
- {
- //将文本文件的各行读到一个字符串数组中
- string[] rows = File.ReadAllLines(filePath);
- //返回行数
- return rows.Length;
- }
- #endregion
- #region 获取一个文件的长度
- /// <summary>
- /// 获取一个文件的长度,单位为Byte
- /// </summary>
- /// <param name="filePath">文件的绝对路径</param>
- public static int GetFileSize(string filePath)
- {
- //创建一个文件对象
- FileInfo fi = new FileInfo(filePath);
- //获取文件的大小
- return (int)fi.Length;
- }
- /// <summary>
- /// 获取一个文件的长度,单位为KB
- /// </summary>
- /// <param name="filePath">文件的路径</param>
- public static double GetFileSizeByKB(string filePath)
- {
- //创建一个文件对象
- FileInfo fi = new FileInfo(filePath);
- long size = fi.Length / 1024;
- //获取文件的大小
- return double.Parse(size.ToString());
- }
- /// <summary>
- /// 获取一个文件的长度,单位为MB
- /// </summary>
- /// <param name="filePath">文件的路径</param>
- public static double GetFileSizeByMB(string filePath)
- {
- //创建一个文件对象
- FileInfo fi = new FileInfo(filePath);
- long size = fi.Length / 1024 / 1024;
- //获取文件的大小
- return double.Parse(size.ToString());
- }
- #endregion
- #region 获取指定目录中的文件列表
- /// <summary>
- /// 获取指定目录中所有文件列表
- /// </summary>
- /// <param name="directoryPath">指定目录的绝对路径</param>
- public static string[] GetFileNames(string directoryPath)
- {
- //如果目录不存在,则抛出异常
- if (!IsExistDirectory(directoryPath))
- {
- throw new FileNotFoundException();
- }
- //获取文件列表
- return Directory.GetFiles(directoryPath);
- }
- /// <summary>
- /// 获取指定目录及子目录中所有文件列表
- /// </summary>
- /// <param name="directoryPath">指定目录的绝对路径</param>
- /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
- /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>
- /// <param name="isSearchChild">是否搜索子目录</param>
- public static string[] GetFileNames(string directoryPath, string searchPattern, bool isSearchChild)
- {
- //如果目录不存在,则抛出异常
- if (!IsExistDirectory(directoryPath))
- {
- throw new FileNotFoundException();
- }
- try
- {
- return Directory.GetFiles(directoryPath, searchPattern, isSearchChild ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
- }
- catch
- {
- return null;
- }
- }
- #endregion
- #region 获取指定目录中的子目录列表
- /// <summary>
- /// 获取指定目录中所有子目录列表,若要搜索嵌套的子目录列表,请使用重载方法.
- /// </summary>
- /// <param name="directoryPath">指定目录的绝对路径</param>
- public static string[] GetDirectories(string directoryPath)
- {
- try
- {
- return Directory.GetDirectories(directoryPath);
- }
- catch
- {
- return null;
- }
- }
- /// <summary>
- /// 获取指定目录及子目录中所有子目录列表
- /// </summary>
- /// <param name="directoryPath">指定目录的绝对路径</param>
- /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
- /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>
- /// <param name="isSearchChild">是否搜索子目录</param>
- public static string[] GetDirectories(string directoryPath, string searchPattern, bool isSearchChild)
- {
- try
- {
- return Directory.GetDirectories(directoryPath, searchPattern, isSearchChild ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
- }
- catch
- {
- throw null;
- }
- }
- #endregion
- #region 向文本文件写入内容
- /// <summary>
- /// 向文本文件中写入内容
- /// </summary>
- /// <param name="filePath">文件的绝对路径</param>
- /// <param name="content">写入的内容</param>
- public static void WriteText(string filePath, string content)
- {
- //向文件写入内容
- File.WriteAllText(filePath, content);
- }
- #endregion
- #region 向文本文件的尾部追加内容
- /// <summary>
- /// 向文本文件的尾部追加内容
- /// </summary>
- /// <param name="filePath">文件的绝对路径</param>
- /// <param name="content">写入的内容</param>
- public static void AppendText(string filePath, string content)
- {
- File.AppendAllText(filePath, content);
- }
- #endregion
- #region 将现有文件的内容复制到新文件中
- /// <summary>
- /// 将源文件的内容复制到目标文件中
- /// </summary>
- /// <param name="sourceFilePath">源文件的绝对路径</param>
- /// <param name="destFilePath">目标文件的绝对路径</param>
- public static void Copy(string sourceFilePath, string destFilePath)
- {
- File.Copy(sourceFilePath, destFilePath, true);
- }
- #endregion
- #region 将文件移动到指定目录
- /// <summary>
- /// 将文件移动到指定目录
- /// </summary>
- /// <param name="sourceFilePath">需要移动的源文件的绝对路径</param>
- /// <param name="descDirectoryPath">移动到的目录的绝对路径</param>
- public static void Move(string sourceFilePath, string descDirectoryPath)
- {
- //获取源文件的名称
- string sourceFileName = GetFileName(sourceFilePath);
- if (IsExistDirectory(descDirectoryPath))
- {
- //如果目标中存在同名文件,则删除
- if (IsExistFile(descDirectoryPath + "\\" + sourceFileName))
- {
- DeleteFile(descDirectoryPath + "\\" + sourceFileName);
- }
- //将文件移动到指定目录
- File.Move(sourceFilePath, descDirectoryPath + "\\" + sourceFileName);
- }
- }
- #endregion
- #region 将流读取到缓冲区中
- /// <summary>
- /// 将流读取到缓冲区中
- /// </summary>
- /// <param name="stream">原始流</param>
- public static byte[] StreamToBytes(Stream stream)
- {
- try
- {
- //创建缓冲区
- byte[] buffer = new byte[stream.Length];
- //读取流
- stream.Read(buffer, 0, int.Parse(stream.Length.ToString()));
- //返回流
- return buffer;
- }
- catch
- {
- return null;
- }
- finally
- {
- //关闭流
- stream.Close();
- }
- }
- #endregion
- #region 将文件读取到缓冲区中
- /// <summary>
- /// 将文件读取到缓冲区中
- /// </summary>
- /// <param name="filePath">文件的绝对路径</param>
- public static byte[] FileToBytes(string filePath)
- {
- //获取文件的大小
- int fileSize = GetFileSize(filePath);
- //创建一个临时缓冲区
- byte[] buffer = new byte[fileSize];
- //创建一个文件流
- FileInfo fi = new FileInfo(filePath);
- FileStream fs = fi.Open(FileMode.Open);
- try
- {
- //将文件流读入缓冲区
- fs.Read(buffer, 0, fileSize);
- return buffer;
- }
- catch
- {
- return null;
- }
- finally
- {
- //关闭文件流
- fs.Close();
- }
- }
- #endregion
- #region 将文件读取到字符串中
- /// <summary>
- /// 将文件读取到字符串中
- /// </summary>
- /// <param name="filePath">文件的绝对路径</param>
- public static string FileToString(string filePath)
- {
- return FileToString(filePath, Encoding.Default);
- }
- /// <summary>
- /// 将文件读取到字符串中
- /// </summary>
- /// <param name="filePath">文件的绝对路径</param>
- /// <param name="encoding">字符编码</param>
- public static string FileToString(string filePath, Encoding encoding)
- {
- //创建流读取器
- StreamReader reader = new StreamReader(filePath, encoding);
- try
- {
- //读取流
- return reader.ReadToEnd();
- }
- catch
- {
- return string.Empty;
- }
- finally
- {
- //关闭流读取器
- reader.Close();
- }
- }
- #endregion
- #region 从文件的绝对路径中获取文件名( 包含扩展名 )
- /// <summary>
- /// 从文件的绝对路径中获取文件名( 包含扩展名 )
- /// </summary>
- /// <param name="filePath">文件的绝对路径</param>
- public static string GetFileName(string filePath)
- {
- //获取文件的名称
- FileInfo fi = new FileInfo(filePath);
- return fi.Name;
- }
- #endregion
- #region 从文件的绝对路径中获取文件名( 不包含扩展名 )
- /// <summary>
- /// 从文件的绝对路径中获取文件名( 不包含扩展名 )
- /// </summary>
- /// <param name="filePath">文件的绝对路径</param>
- public static string GetFileNameNoExtension(string filePath)
- {
- //获取文件的名称
- FileInfo fi = new FileInfo(filePath);
- return fi.Name.Split('.')[0];
- }
- #endregion
- #region 从文件的绝对路径中获取扩展名
- /// <summary>
- /// 从文件的绝对路径中获取扩展名
- /// </summary>
- /// <param name="filePath">文件的绝对路径</param>
- public static string GetExtension(string filePath)
- {
- //获取文件的名称
- FileInfo fi = new FileInfo(filePath);
- return fi.Extension;
- }
- #endregion
- #region 清空指定目录
- /// <summary>
- /// 清空指定目录下所有文件及子目录,但该目录依然保存.
- /// </summary>
- /// <param name="directoryPath">指定目录的绝对路径</param>
- public static void ClearDirectory(string directoryPath)
- {
- if (IsExistDirectory(directoryPath))
- {
- //删除目录中所有的文件
- string[] fileNames = GetFileNames(directoryPath);
- foreach (string t in fileNames)
- {
- DeleteFile(t);
- }
- //删除目录中所有的子目录
- string[] directoryNames = GetDirectories(directoryPath);
- foreach (string t in directoryNames)
- {
- DeleteDirectory(t);
- }
- }
- }
- #endregion
- #region 清空文件内容
- /// <summary>
- /// 清空文件内容
- /// </summary>
- /// <param name="filePath">文件的绝对路径</param>
- public static void ClearFile(string filePath)
- {
- //删除文件
- File.Delete(filePath);
- //重新创建该文件
- CreateFile(filePath);
- }
- #endregion
- #region 删除指定文件
- /// <summary>
- /// 删除指定文件
- /// </summary>
- /// <param name="filePath">文件的绝对路径</param>
- public static void DeleteFile(string filePath)
- {
- if (IsExistFile(filePath))
- {
- File.Delete(filePath);
- }
- }
- #endregion
- #region 删除指定目录
- /// <summary>
- /// 删除指定目录及其所有子目录
- /// </summary>
- /// <param name="directoryPath">指定目录的绝对路径</param>
- public static void DeleteDirectory(string directoryPath)
- {
- if (IsExistDirectory(directoryPath))
- {
- Directory.Delete(directoryPath, true);
- }
- }
- #endregion
- #region 记录错误日志到文件方法
- /// <summary>
- /// 记录错误日志到文件方法
- /// </summary>
- /// <param name="exMessage"></param>
- /// <param name="exMethod"></param>
- /// <param name="userID"></param>
- public static void ErrorLog(string exMessage, string exMethod, int userID)
- {
- try
- {
- string errVir = "/Log/Error/" + DateTime.Now.ToShortDateString() + ".txt";
- string errPath = System.Web.HttpContext.Current.Server.MapPath(errVir);
- File.AppendAllText(errPath,
- "{userID:" + userID + ",exMedthod:" + exMethod + ",exMessage:" + exMessage + "}");
- }
- catch
- {
- }
- }
- #endregion
- #region 输出调试日志
- /// <summary>
- /// 输出调试日志
- /// </summary>
- /// <param name="factValue">实际值</param>
- /// <param name="expectValue">预期值</param>
- public static void OutDebugLog(object factValue, object expectValue = null)
- {
- string errPath = System.Web.HttpContext.Current.Server.MapPath(string.Format("/Log/Debug/{0}.html", DateTime.Now.ToShortDateString()));
- if (!Equals(expectValue, null))
- File.AppendAllLines(errPath,
- new[]{string.Format(
- "【{0}】[{3}] 实际值:<span style='color:blue;'>{1}</span> 预期值: <span style='color:gray;'>{2}</span><br/>",
- DateTime.Now.ToShortTimeString()
- , factValue, expectValue, Equals(expectValue, factValue)
- ? "<span style='color:green;'>成功</span>"
- : "<span style='color:red;'>失败</span>")});
- else
- File.AppendAllLines(errPath, new[]{
- string.Format(
- "【{0}】[{3}] 实际值:<span style='color:blue;'>{1}</span> 预期值: <span style='color:gray;'>{2}</span><br/>",
- DateTime.Now.ToShortTimeString()
- , factValue, "空", "<span style='color:green;'>成功</span>")});
- }
- #endregion
- }
- }
c# 文件及目录操作类的更多相关文章
- Python之文件与目录操作及压缩模块(os、shutil、zipfile、tarfile)
Python中可以用于对文件和目录进行操作的内置模块包括: 模块/函数名称 功能描述 open()函数 文件读取或写入 os.path模块 文件路径操作 os模块 文件和目录简单操作 zipfile模 ...
- 【转】Python之文件与目录操作(os、zipfile、tarfile、shutil)
[转]Python之文件与目录操作(os.zipfile.tarfile.shutil) Python中可以用于对文件和目录进行操作的内置模块包括: 模块/函数名称 功能描述 open()函数 文件读 ...
- Python之文件与目录操作(os、zipfile、tarfile、shutil)
Python中可以用于对文件和目录进行操作的内置模块包括: 模块/函数名称 功能描述 open()函数 文件读取或写入 os.path模块 文件路径操作 os模块 文件和目录简单操作 zipfile模 ...
- Java编程的逻辑 (59) - 文件和目录操作
本系列文章经补充和完善,已修订整理成书<Java编程的逻辑>,由机械工业出版社华章分社出版,于2018年1月上市热销,读者好评如潮!各大网店和书店有售,欢迎购买,京东自营链接:http:/ ...
- Python::OS 模块 -- 文件和目录操作
os模块的简介参看 Python::OS 模块 -- 简介 os模块的进程管理 Python::OS 模块 -- 进程管理 os模块的进程参数 Python::OS 模块 -- 进程参数 os模块中包 ...
- 零基础学Python--------第10章 文件及目录操作
第10章 文件及目录操作 10.1 基本文件操作 在Python中,内置了文件(File)对象.在使用文件对象时,首先需要通过内置的open() 方法创建一个文件对象,然后通过对象提供的方法进行一些基 ...
- Shell命令-文件及目录操作之ls、cd
文件及目录操作 - ls.cd 1.ls:列出目录的内容及其内容属性信息 ls命令的功能说明 ls命令用于列出目录的内容及其内容属性信息. ls命令的语法格式 ls [OPTION]... [FILE ...
- Shell命令-文件及目录操作之cp、find
文件及目录操作 - cp.find 1.cp:复制文件或目录 cp命令的功能说明 cp命令用于复制文件或目录. cp命令的语法格式 cp [OPTION]... SOURCE... DIRECTORY ...
- Shell命令-文件及目录操作之mkdir、mv
文件及目录操作 - mkdir.mv 1.mkdir:创建目录 mkdir命令的功能说明 mkdir命令用于创建目录,默认情况下,要创建的目录已存在,会提示文件存在,不会继续创建目录. mkdir命令 ...
随机推荐
- Github账户注册的过程
首先我通过冯老师的博客园帖子中的链接进入了注册地址,填写了用户名,邮箱,和密码.然后我进入我的邮箱验证了Github网站给我发送的验证信息,至此,我的GITHUB账户便注册完成了.
- 学韩顺平老师linux教程--笔记
第二讲:1.startx 进入图形界面2.shutdown -h now 立刻进行关机3.shutdown -r now 现在重新启动计算机4.reboot 现在重新启动计算机5. ...
- WCF初体验(C#操作Exchange)
最近再做一个Exchange的客户端维护工具,遇到了很多问题. 由于刚接触C#和Exchange,所以还需要继续学习.在此记录一下,只是一个新手的记录. 环境: 服务器:Exchang ...
- 使用snmp+mrtg监控CPU、流量、磁盘空间、内存
1.安装snmp rpm -qa|grep snmp* //查看是否安装了snmpyum -y install snmp* //安装snmp #vim /etc/snmp/snmpd.confroco ...
- MYSQL权限表user操作
MYSQL权限表user cmd中进人mysql找到mysql安装目录 E:\wamp\bin\mysql\mysql5.6.12\bin>mysql.exe -u 用户名 - ...
- 验证视图状态MAC失败。如果此应用程序由网络场或群集承载,请确保配置指定了相同的validationKey和验证算法(转)
原文转自:http://www.cnblogs.com/Setme/archive/2012/06/05/2537084.html 验证视图状态 MAC 失败.如果此应用程序由网络场或群集承载,请确保 ...
- vim 高亮显示配置
/etc/vim/vimrc set showmatch "bracket matchset matchtime=5 "bracket match time 5 set ignor ...
- 创建COM对象时遭遇 800702e4
SolidEdge st5(x64) SDK /vs2012/win8.1 x64 西夏普创建SEApplication COM对象时遭遇800702e4.翻来覆去的调vs进程的权限,调se进程的权限 ...
- Registry values for ProductID and LocaleID for AutoCAD and the vertical products
原文地址:http://adndevblog.typepad.com/autocad/2013/08/registry-values-for-productid-and-localeid-for-au ...
- 应用C#和SQLCLR编写SQL Server用户定义函数
摘要: 文档阐述使用C#和SQLCLR为SQL Server编写用户定义函数,并演示用户定义函数在T-SQL中的应用.文档中实现的 Base64 编码解码函数和正则表达式函数属于标量值函数,字符串分割 ...