c# 文件及目录操作类

18位长度的计时周期数: DateTime.Now.Ticks.ToString()

多数是收集而来,加上测试感觉很不错,分享一下或许有些帮助吧:

引用:

[csharp] view plain copy
  1. using System;  
  2. using System.Text;  
  3. using System.IO;  


主代码:

[csharp] view plain copy
  1. namespace PorjectTools  
  2. {  
  3.     ///<summary>  
  4.     ///</summary>  
  5.     public static class FileHelper  
  6.     {  
  7.         #region 检测指定目录是否存在  
  8.         /// <summary>  
  9.         /// 检测指定目录是否存在  
  10.         /// </summary>  
  11.         /// <param name="directoryPath">目录的绝对路径</param>          
  12.         public static bool IsExistDirectory(string directoryPath)  
  13.         {  
  14.             return Directory.Exists(directoryPath);  
  15.         }  
  16.         #endregion  
  17.  
  18.         #region 检测指定文件是否存在  
  19.         /// <summary>  
  20.         /// 检测指定文件是否存在,如果存在则返回true。  
  21.         /// </summary>  
  22.         /// <param name="filePath">文件的绝对路径</param>          
  23.         public static bool IsExistFile(string filePath)  
  24.         {  
  25.             return File.Exists(filePath);  
  26.         }  
  27.         #endregion  
  28.  
  29.         #region 检测指定目录是否为空  
  30.         /// <summary>  
  31.         /// 检测指定目录是否为空  
  32.         /// </summary>  
  33.         /// <param name="directoryPath">指定目录的绝对路径</param>          
  34.         public static bool IsEmptyDirectory(string directoryPath)  
  35.         {  
  36.             try  
  37.             {  
  38.                 //判断是否存在文件  
  39.                 string[] fileNames = GetFileNames(directoryPath);  
  40.                 if (fileNames.Length > 0)  
  41.                 {  
  42.                     return false;  
  43.                 }  
  44.   
  45.                 //判断是否存在文件夹  
  46.                 string[] directoryNames = GetDirectories(directoryPath);  
  47.                 return directoryNames.Length <= 0;  
  48.             }  
  49.             catch  
  50.             {  
  51.                 return false;  
  52.             }  
  53.         }  
  54.         #endregion  
  55.  
  56.         #region 检测指定目录中是否存在指定的文件  
  57.         /// <summary>  
  58.         /// 检测指定目录中是否存在指定的文件,若要搜索子目录请使用重载方法.  
  59.         /// </summary>  
  60.         /// <param name="directoryPath">指定目录的绝对路径</param>  
  61.         /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。  
  62.         /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>          
  63.         public static bool Contains(string directoryPath, string searchPattern)  
  64.         {  
  65.             try  
  66.             {  
  67.                 //获取指定的文件列表  
  68.                 string[] fileNames = GetFileNames(directoryPath, searchPattern, false);  
  69.   
  70.                 //判断指定文件是否存在  
  71.                 return fileNames.Length != 0;  
  72.             }  
  73.             catch  
  74.             {  
  75.                 return false;  
  76.             }  
  77.         }  
  78.   
  79.         /// <summary>  
  80.         /// 检测指定目录中是否存在指定的文件  
  81.         /// </summary>  
  82.         /// <param name="directoryPath">指定目录的绝对路径</param>  
  83.         /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。  
  84.         /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>   
  85.         /// <param name="isSearchChild">是否搜索子目录</param>  
  86.         public static bool Contains(string directoryPath, string searchPattern, bool isSearchChild)  
  87.         {  
  88.             try  
  89.             {  
  90.                 //获取指定的文件列表  
  91.                 string[] fileNames = GetFileNames(directoryPath, searchPattern, true);  
  92.   
  93.                 //判断指定文件是否存在  
  94.                 return fileNames.Length != 0;  
  95.             }  
  96.             catch  
  97.             {  
  98.                 return false;  
  99.             }  
  100.         }  
  101.         #endregion  
  102.  
  103.         #region 创建一个目录  
  104.         /// <summary>  
  105.         /// 创建一个目录  
  106.         /// </summary>  
  107.         /// <param name="directoryPath">目录的绝对路径</param>  
  108.         public static void CreateDirectory(string directoryPath)  
  109.         {  
  110.             //如果目录不存在则创建该目录  
  111.             if (!IsExistDirectory(directoryPath))  
  112.             {  
  113.                 Directory.CreateDirectory(directoryPath);  
  114.             }  
  115.         }  
  116.         #endregion  
  117.  
  118.         #region 创建一个文件  
  119.         /// <summary>  
  120.         /// 创建一个文件。  
  121.         /// </summary>  
  122.         /// <param name="filePath">文件的绝对路径</param>  
  123.         public static bool CreateFile(string filePath)  
  124.         {  
  125.             try  
  126.             {  
  127.                 //如果文件不存在则创建该文件  
  128.                 if (!IsExistFile(filePath))  
  129.                 {  
  130.                     //创建一个FileInfo对象  
  131.                     FileInfo file = new FileInfo(filePath);  
  132.                     //创建文件  
  133.                     FileStream fs = file.Create();  
  134.                     //关闭文件流  
  135.                     fs.Close();  
  136.                 }  
  137.             }  
  138.             catch  
  139.             {  
  140.                 return false;  
  141.             }  
  142.   
  143.             return true;  
  144.         }  
  145.   
  146.         /// <summary>  
  147.         /// 创建一个文件,并将字节流写入文件。  
  148.         /// </summary>  
  149.         /// <param name="filePath">文件的绝对路径</param>  
  150.         /// <param name="buffer">二进制流数据</param>  
  151.         public static bool CreateFile(string filePath, byte[] buffer)  
  152.         {  
  153.             try  
  154.             {  
  155.                 //如果文件不存在则创建该文件  
  156.                 if (!IsExistFile(filePath))  
  157.                 {  
  158.                     //创建一个FileInfo对象  
  159.                     FileInfo file = new FileInfo(filePath);  
  160.   
  161.                     //创建文件  
  162.                     FileStream fs = file.Create();  
  163.   
  164.                     //写入二进制流  
  165.                     fs.Write(buffer, 0, buffer.Length);  
  166.   
  167.                     //关闭文件流  
  168.                     fs.Close();  
  169.                 }  
  170.             }  
  171.             catch  
  172.             {  
  173.                 return false;  
  174.             }  
  175.             return true;  
  176.         }  
  177.         #endregion  
  178.  
  179.         #region 获取文本文件的行数  
  180.         /// <summary>  
  181.         /// 获取文本文件的行数  
  182.         /// </summary>  
  183.         /// <param name="filePath">文件的绝对路径</param>          
  184.         public static int GetLineCount(string filePath)  
  185.         {  
  186.             //将文本文件的各行读到一个字符串数组中  
  187.             string[] rows = File.ReadAllLines(filePath);  
  188.   
  189.             //返回行数  
  190.             return rows.Length;  
  191.         }  
  192.         #endregion  
  193.  
  194.         #region 获取一个文件的长度  
  195.         /// <summary>  
  196.         /// 获取一个文件的长度,单位为Byte  
  197.         /// </summary>  
  198.         /// <param name="filePath">文件的绝对路径</param>          
  199.         public static int GetFileSize(string filePath)  
  200.         {  
  201.             //创建一个文件对象  
  202.             FileInfo fi = new FileInfo(filePath);  
  203.   
  204.             //获取文件的大小  
  205.             return (int)fi.Length;  
  206.         }  
  207.   
  208.         /// <summary>  
  209.         /// 获取一个文件的长度,单位为KB  
  210.         /// </summary>  
  211.         /// <param name="filePath">文件的路径</param>          
  212.         public static double GetFileSizeByKB(string filePath)  
  213.         {  
  214.             //创建一个文件对象  
  215.             FileInfo fi = new FileInfo(filePath);  
  216.             long size = fi.Length / 1024;  
  217.             //获取文件的大小  
  218.             return double.Parse(size.ToString());  
  219.         }  
  220.   
  221.         /// <summary>  
  222.         /// 获取一个文件的长度,单位为MB  
  223.         /// </summary>  
  224.         /// <param name="filePath">文件的路径</param>          
  225.         public static double GetFileSizeByMB(string filePath)  
  226.         {  
  227.             //创建一个文件对象  
  228.             FileInfo fi = new FileInfo(filePath);  
  229.             long size = fi.Length / 1024 / 1024;  
  230.             //获取文件的大小  
  231.             return double.Parse(size.ToString());  
  232.         }  
  233.         #endregion  
  234.  
  235.         #region 获取指定目录中的文件列表  
  236.         /// <summary>  
  237.         /// 获取指定目录中所有文件列表  
  238.         /// </summary>  
  239.         /// <param name="directoryPath">指定目录的绝对路径</param>          
  240.         public static string[] GetFileNames(string directoryPath)  
  241.         {  
  242.             //如果目录不存在,则抛出异常  
  243.             if (!IsExistDirectory(directoryPath))  
  244.             {  
  245.                 throw new FileNotFoundException();  
  246.             }  
  247.   
  248.             //获取文件列表  
  249.             return Directory.GetFiles(directoryPath);  
  250.         }  
  251.   
  252.         /// <summary>  
  253.         /// 获取指定目录及子目录中所有文件列表  
  254.         /// </summary>  
  255.         /// <param name="directoryPath">指定目录的绝对路径</param>  
  256.         /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。  
  257.         /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>  
  258.         /// <param name="isSearchChild">是否搜索子目录</param>  
  259.         public static string[] GetFileNames(string directoryPath, string searchPattern, bool isSearchChild)  
  260.         {  
  261.             //如果目录不存在,则抛出异常  
  262.             if (!IsExistDirectory(directoryPath))  
  263.             {  
  264.                 throw new FileNotFoundException();  
  265.             }  
  266.   
  267.             try  
  268.             {  
  269.                 return Directory.GetFiles(directoryPath, searchPattern, isSearchChild ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);  
  270.             }  
  271.             catch  
  272.             {  
  273.                 return null;  
  274.             }  
  275.         }  
  276.         #endregion  
  277.  
  278.         #region 获取指定目录中的子目录列表  
  279.         /// <summary>  
  280.         /// 获取指定目录中所有子目录列表,若要搜索嵌套的子目录列表,请使用重载方法.  
  281.         /// </summary>  
  282.         /// <param name="directoryPath">指定目录的绝对路径</param>          
  283.         public static string[] GetDirectories(string directoryPath)  
  284.         {  
  285.             try  
  286.             {  
  287.                 return Directory.GetDirectories(directoryPath);  
  288.             }  
  289.             catch  
  290.             {  
  291.                 return null;  
  292.             }  
  293.         }  
  294.   
  295.         /// <summary>  
  296.         /// 获取指定目录及子目录中所有子目录列表  
  297.         /// </summary>  
  298.         /// <param name="directoryPath">指定目录的绝对路径</param>  
  299.         /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。  
  300.         /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>  
  301.         /// <param name="isSearchChild">是否搜索子目录</param>  
  302.         public static string[] GetDirectories(string directoryPath, string searchPattern, bool isSearchChild)  
  303.         {  
  304.             try  
  305.             {  
  306.                 return Directory.GetDirectories(directoryPath, searchPattern, isSearchChild ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);  
  307.             }  
  308.             catch  
  309.             {  
  310.                 throw null;  
  311.             }  
  312.         }  
  313.         #endregion  
  314.  
  315.         #region 向文本文件写入内容  
  316.         /// <summary>  
  317.         /// 向文本文件中写入内容  
  318.         /// </summary>  
  319.         /// <param name="filePath">文件的绝对路径</param>  
  320.         /// <param name="content">写入的内容</param>          
  321.         public static void WriteText(string filePath, string content)  
  322.         {  
  323.             //向文件写入内容  
  324.             File.WriteAllText(filePath, content);  
  325.         }  
  326.         #endregion  
  327.  
  328.         #region 向文本文件的尾部追加内容  
  329.         /// <summary>  
  330.         /// 向文本文件的尾部追加内容  
  331.         /// </summary>  
  332.         /// <param name="filePath">文件的绝对路径</param>  
  333.         /// <param name="content">写入的内容</param>  
  334.         public static void AppendText(string filePath, string content)  
  335.         {  
  336.             File.AppendAllText(filePath, content);  
  337.         }  
  338.         #endregion  
  339.  
  340.         #region 将现有文件的内容复制到新文件中  
  341.         /// <summary>  
  342.         /// 将源文件的内容复制到目标文件中  
  343.         /// </summary>  
  344.         /// <param name="sourceFilePath">源文件的绝对路径</param>  
  345.         /// <param name="destFilePath">目标文件的绝对路径</param>  
  346.         public static void Copy(string sourceFilePath, string destFilePath)  
  347.         {  
  348.             File.Copy(sourceFilePath, destFilePath, true);  
  349.         }  
  350.         #endregion  
  351.  
  352.         #region 将文件移动到指定目录  
  353.         /// <summary>  
  354.         /// 将文件移动到指定目录  
  355.         /// </summary>  
  356.         /// <param name="sourceFilePath">需要移动的源文件的绝对路径</param>  
  357.         /// <param name="descDirectoryPath">移动到的目录的绝对路径</param>  
  358.         public static void Move(string sourceFilePath, string descDirectoryPath)  
  359.         {  
  360.             //获取源文件的名称  
  361.             string sourceFileName = GetFileName(sourceFilePath);  
  362.   
  363.             if (IsExistDirectory(descDirectoryPath))  
  364.             {  
  365.                 //如果目标中存在同名文件,则删除  
  366.                 if (IsExistFile(descDirectoryPath + "\" + sourceFileName))  
  367.                 {  
  368.                     DeleteFile(descDirectoryPath + "\" + sourceFileName);  
  369.                 }  
  370.                 //将文件移动到指定目录  
  371.                 File.Move(sourceFilePath, descDirectoryPath + "\" + sourceFileName);  
  372.             }  
  373.         }  
  374.         #endregion  
  375.  
  376.         #region 将流读取到缓冲区中  
  377.         /// <summary>  
  378.         /// 将流读取到缓冲区中  
  379.         /// </summary>  
  380.         /// <param name="stream">原始流</param>  
  381.         public static byte[] StreamToBytes(Stream stream)  
  382.         {  
  383.             try  
  384.             {  
  385.                 //创建缓冲区  
  386.                 byte[] buffer = new byte[stream.Length];  
  387.   
  388.                 //读取流  
  389.                 stream.Read(buffer, 0, int.Parse(stream.Length.ToString()));  
  390.   
  391.                 //返回流  
  392.                 return buffer;  
  393.             }  
  394.             catch  
  395.             {  
  396.                 return null;  
  397.             }  
  398.             finally  
  399.             {  
  400.                 //关闭流  
  401.                 stream.Close();  
  402.             }  
  403.         }  
  404.         #endregion  
  405.  
  406.         #region 将文件读取到缓冲区中  
  407.         /// <summary>  
  408.         /// 将文件读取到缓冲区中  
  409.         /// </summary>  
  410.         /// <param name="filePath">文件的绝对路径</param>  
  411.         public static byte[] FileToBytes(string filePath)  
  412.         {  
  413.             //获取文件的大小   
  414.             int fileSize = GetFileSize(filePath);  
  415.   
  416.             //创建一个临时缓冲区  
  417.             byte[] buffer = new byte[fileSize];  
  418.   
  419.             //创建一个文件流  
  420.             FileInfo fi = new FileInfo(filePath);  
  421.             FileStream fs = fi.Open(FileMode.Open);  
  422.   
  423.             try  
  424.             {  
  425.                 //将文件流读入缓冲区  
  426.                 fs.Read(buffer, 0, fileSize);  
  427.   
  428.                 return buffer;  
  429.             }  
  430.             catch  
  431.             {  
  432.                 return null;  
  433.             }  
  434.             finally  
  435.             {  
  436.                 //关闭文件流  
  437.                 fs.Close();  
  438.             }  
  439.         }  
  440.         #endregion  
  441.  
  442.         #region 将文件读取到字符串中  
  443.         /// <summary>  
  444.         /// 将文件读取到字符串中  
  445.         /// </summary>  
  446.         /// <param name="filePath">文件的绝对路径</param>  
  447.         public static string FileToString(string filePath)  
  448.         {  
  449.             return FileToString(filePath, Encoding.Default);  
  450.         }  
  451.         /// <summary>  
  452.         /// 将文件读取到字符串中  
  453.         /// </summary>  
  454.         /// <param name="filePath">文件的绝对路径</param>  
  455.         /// <param name="encoding">字符编码</param>  
  456.         public static string FileToString(string filePath, Encoding encoding)  
  457.         {  
  458.             //创建流读取器  
  459.             StreamReader reader = new StreamReader(filePath, encoding);  
  460.             try  
  461.             {  
  462.                 //读取流  
  463.                 return reader.ReadToEnd();  
  464.             }  
  465.             catch  
  466.             {  
  467.                 return string.Empty;  
  468.             }  
  469.             finally  
  470.             {  
  471.                 //关闭流读取器  
  472.                 reader.Close();  
  473.             }  
  474.         }  
  475.         #endregion  
  476.  
  477.         #region 从文件的绝对路径中获取文件名( 包含扩展名 )  
  478.         /// <summary>  
  479.         /// 从文件的绝对路径中获取文件名( 包含扩展名 )  
  480.         /// </summary>  
  481.         /// <param name="filePath">文件的绝对路径</param>          
  482.         public static string GetFileName(string filePath)  
  483.         {  
  484.             //获取文件的名称  
  485.             FileInfo fi = new FileInfo(filePath);  
  486.             return fi.Name;  
  487.         }  
  488.         #endregion  
  489.  
  490.         #region 从文件的绝对路径中获取文件名( 不包含扩展名 )  
  491.         /// <summary>  
  492.         /// 从文件的绝对路径中获取文件名( 不包含扩展名 )  
  493.         /// </summary>  
  494.         /// <param name="filePath">文件的绝对路径</param>          
  495.         public static string GetFileNameNoExtension(string filePath)  
  496.         {  
  497.             //获取文件的名称  
  498.             FileInfo fi = new FileInfo(filePath);  
  499.             return fi.Name.Split('.')[0];  
  500.         }  
  501.         #endregion  
  502.  
  503.         #region 从文件的绝对路径中获取扩展名  
  504.         /// <summary>  
  505.         /// 从文件的绝对路径中获取扩展名  
  506.         /// </summary>  
  507.         /// <param name="filePath">文件的绝对路径</param>          
  508.         public static string GetExtension(string filePath)  
  509.         {  
  510.             //获取文件的名称  
  511.             FileInfo fi = new FileInfo(filePath);  
  512.             return fi.Extension;  
  513.         }  
  514.         #endregion  
  515.  
  516.         #region 清空指定目录  
  517.         /// <summary>  
  518.         /// 清空指定目录下所有文件及子目录,但该目录依然保存.  
  519.         /// </summary>  
  520.         /// <param name="directoryPath">指定目录的绝对路径</param>  
  521.         public static void ClearDirectory(string directoryPath)  
  522.         {  
  523.             if (IsExistDirectory(directoryPath))  
  524.             {  
  525.                 //删除目录中所有的文件  
  526.                 string[] fileNames = GetFileNames(directoryPath);  
  527.                 foreach (string t in fileNames)  
  528.                 {  
  529.                     DeleteFile(t);  
  530.                 }  
  531.   
  532.                 //删除目录中所有的子目录  
  533.                 string[] directoryNames = GetDirectories(directoryPath);  
  534.                 foreach (string t in directoryNames)  
  535.                 {  
  536.                     DeleteDirectory(t);  
  537.                 }  
  538.             }  
  539.         }  
  540.         #endregion  
  541.  
  542.         #region 清空文件内容  
  543.         /// <summary>  
  544.         /// 清空文件内容  
  545.         /// </summary>  
  546.         /// <param name="filePath">文件的绝对路径</param>  
  547.         public static void ClearFile(string filePath)  
  548.         {  
  549.             //删除文件  
  550.             File.Delete(filePath);  
  551.   
  552.             //重新创建该文件  
  553.             CreateFile(filePath);  
  554.         }  
  555.         #endregion  
  556.  
  557.         #region 删除指定文件  
  558.         /// <summary>  
  559.         /// 删除指定文件  
  560.         /// </summary>  
  561.         /// <param name="filePath">文件的绝对路径</param>  
  562.         public static void DeleteFile(string filePath)  
  563.         {  
  564.             if (IsExistFile(filePath))  
  565.             {  
  566.                 File.Delete(filePath);  
  567.             }  
  568.         }  
  569.         #endregion  
  570.  
  571.         #region 删除指定目录  
  572.         /// <summary>  
  573.         /// 删除指定目录及其所有子目录  
  574.         /// </summary>  
  575.         /// <param name="directoryPath">指定目录的绝对路径</param>  
  576.         public static void DeleteDirectory(string directoryPath)  
  577.         {  
  578.             if (IsExistDirectory(directoryPath))  
  579.             {  
  580.                 Directory.Delete(directoryPath, true);  
  581.             }  
  582.         }  
  583.         #endregion  
  584.  
  585.         #region 记录错误日志到文件方法  
  586.         /// <summary>  
  587.         /// 记录错误日志到文件方法  
  588.         /// </summary>  
  589.         /// <param name="exMessage"></param>  
  590.         /// <param name="exMethod"></param>  
  591.         /// <param name="userID"></param>  
  592.         public static void ErrorLog(string exMessage, string exMethod, int userID)  
  593.         {  
  594.             try  
  595.             {  
  596.                 string errVir = "/Log/Error/" + DateTime.Now.ToShortDateString() + ".txt";  
  597.                 string errPath = System.Web.HttpContext.Current.Server.MapPath(errVir);  
  598.                 File.AppendAllText(errPath,  
  599.                                    "{userID:" + userID + ",exMedthod:" + exMethod + ",exMessage:" + exMessage + "}");  
  600.             }  
  601.             catch  
  602.             {  
  603.   
  604.             }  
  605.         }  
  606.         #endregion  
  607.  
  608.         #region 输出调试日志  
  609.         /// <summary>  
  610.         /// 输出调试日志  
  611.         /// </summary>  
  612.         /// <param name="factValue">实际值</param>   
  613.         /// <param name="expectValue">预期值</param>  
  614.         public static void OutDebugLog(object factValue, object expectValue = null)  
  615.         {  
  616.             string errPath = System.Web.HttpContext.Current.Server.MapPath(string.Format("/Log/Debug/{0}.html", DateTime.Now.ToShortDateString()));  
  617.             if (!Equals(expectValue, null))  
  618.                 File.AppendAllLines(errPath,  
  619.                                    new[]{string.Format(  
  620.                                        "【{0}】[{3}] 实际值:<span style='color:blue;'>{1}</span> 预期值: <span style='color:gray;'>{2}</span><br/>",  
  621.                                        DateTime.Now.ToShortTimeString()  
  622.                                        , factValue, expectValue, Equals(expectValue, factValue)  
  623.                                            ? "<span style='color:green;'>成功</span>"  
  624.                                            : "<span style='color:red;'>失败</span>")});  
  625.             else  
  626.                 File.AppendAllLines(errPath, new[]{  
  627.                                string.Format(  
  628.                                    "【{0}】[{3}] 实际值:<span style='color:blue;'>{1}</span> 预期值: <span style='color:gray;'>{2}</span><br/>",  
  629.                                    DateTime.Now.ToShortTimeString()  
  630.                                    , factValue, "空", "<span style='color:green;'>成功</span>")});  
  631.         }  
  632.         #endregion  
  633.     }  
  634. }  
原文地址:https://www.cnblogs.com/host-2008/p/5937799.html