c#文件助手类分享(读取文件内容 操作日志文件)

代码如下:

using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Linq;
using System.Runtime.InteropServices;
namespace Humep.FileWatcher
{
    /// <summary>
    /// 日志文件操作
    /// Date:2011-06-01
    /// </summary>
    public static class FileHelper
    {
        /// <summary>
        /// 获取文件路径中最后的目录名
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string GetDirectoryName(string fullName)
        {
            if (string.IsNullOrWhiteSpace(fullName))
            {
                return null;
            }
            return fullName.Substring(0,fullName.LastIndexOf('\\')+1);
        }
        /// <summary>
        /// 获取路径中的文件名称
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string GetFileName(string filePath)
        {
            if (string.IsNullOrWhiteSpace(filePath))
            {
                return string.Empty;
            }
            if (filePath.Length > 260)
            {
                return filePath.Substring(filePath.LastIndexOf('\\') + 1, int.MaxValue);
            }
            return Path.GetFileName(filePath);
        }

/// <summary>
        /// 文件名是否满足filePattern格式。
        /// </summary>
        /// <param name="fileName"></param>
        public static bool IsMatched(string fileName, string filePattern)
        {
            if (string.IsNullOrWhiteSpace(fileName))
            {
                return false;
            }
            if (string.IsNullOrWhiteSpace(filePattern))
            {
                return false;
            }
            Regex regex = new Regex(filePattern, RegexOptions.IgnoreCase);
            return regex.IsMatch(fileName);
        }

/// <summary>
        /// 读取文件内容
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static string ReadAllText(string filePath)
        {
            if (string.IsNullOrWhiteSpace(filePath) || File.Exists(filePath) == false)
            {
                return string.Empty;
            }
            return File.ReadAllText(filePath);
        }
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="filePath"></param>
        public static bool Delete(string filePath)
        {
            if (string.IsNullOrWhiteSpace(filePath))
            {
                return false;
            }
            if (!File.Exists(filePath))
            {
                return false;
            }
            File.Delete(filePath);
            return !File.Exists(filePath);
        }
        /// <summary>
        /// 删除目录下所有过期文件
        /// </summary>
        /// <param name="directory"></param>
        /// <param name="expiredDays"></param>
        public static int ClearExpiredFiles(string directory, int expiredDays)
        {
            if (!Directory.Exists(directory))
            {
                return 0;
            }
            if (expiredDays <= 0)
            {
                return 0;
            }
            DirectoryInfo dir = new DirectoryInfo(directory);
            IList<FileInfo> fileInfos =dir.GetFiles();
            if (fileInfos == null || fileInfos.Count < 1)
            {
                return 0;
            }
            int count = 0;
            foreach (FileInfo fileInfo in fileInfos)
            {
                if (fileInfo.CreationTime.AddDays(expiredDays) < DateTime.Now)
                {
                    //added by yangbinggang
                    fileInfo.Attributes = FileAttributes.Normal;
                    FileHelper.Delete(fileInfo.FullName);
                    count = count + 1;
                }
            }
            return count;
        }
        /// <summary>
        /// 删除目录下所有过期文件
        /// </summary>
        /// <param name="dirs">目录数组</param>
        /// <param name="expiredDays"></param>
        /// <returns></returns>
        public static int ClearExpiredFiles(string[] dirs, int expiredDays)
        {
            if (dirs == null)
            {
                return 0;
            }
            if (dirs.Length <= 0)
            {
                return 0;
            }
            int count = 0;
            foreach (string dir in dirs)
            {
                count = count + ClearExpiredFiles(dir, expiredDays);
            }
            return count;
        }
        /// <summary>
        /// 删除过期目录及其子目录和文件
        /// </summary>
        /// <param name="directories">目录数组</param>
        /// <param name="expiredDays"></param>
        /// <returns></returns>
        public static int ClearExpiredDirectories(string[] directories, int expiredDays)
        {
            if (directories == null || directories.Length <= 0)
            {
                return 0;
            }
            if (expiredDays < 0)
            {
                return 0;
            }
            int count = 0;
            foreach (string directory in directories)
            {
                if (!Directory.Exists(directory))
                {
                    continue;
                }
                count += ClearExpiredFiles(directory, expiredDays);
                DirectoryInfo directoryInfo = new DirectoryInfo(directory);
                if (directoryInfo.CreationTime.AddDays(expiredDays) < DateTime.Now)
                {
                    directoryInfo.Attributes = FileAttributes.Normal;
                    Directory.Delete(directory, true);
                }
            }
            return count;
        }
        /// <summary>
        /// 深度枚举出所有子目录(包括子目录的子目录)
        /// </summary>
        /// <param name="directory"></param>
        /// <returns></returns>
        public static IList<string> EnumerateAllSubDirectories(string directory)
        {
            List<string> direcotryList = new List<string>();
            if (string.IsNullOrWhiteSpace(directory))
            {
                return direcotryList;
            }
            if (!Directory.Exists(directory))
            {
                return direcotryList;
            }

string[] folders = Directory.GetDirectories(directory);
            direcotryList.AddRange(folders);
            foreach (string folder in folders)
            {
                direcotryList.AddRange(EnumerateAllSubDirectories(folder));
            }
            return direcotryList;
        }
        /// <summary>
        /// 根据时间查询文件
        /// </summary>
        /// <param name="directory"></param>
        /// <param name="maxCount"></param>
        /// <returns></returns>
        public static IList<string> FindFiles(string directory, int maxCount, int days)
        {
            IList<string> fileList = new List<string>();
            if (!Directory.Exists(directory) || maxCount <= 0)
            {
                return fileList;
            }
            string[] files = Directory.GetFiles(directory);
            if(files==null)
            {
                return fileList;
            }
            //modified by yangbinggang 2012-12-10  DTS2012121004132\DTS2012121004404\DTS2012121004291
            DateTime lastTime = DateTime.Now.AddDays(-Math.Abs(days));
            fileList = files.Where(item =>
                            {
                                if (maxCount <= 0)
                                {
                                    return false;
                                }
                                FileInfo fileInfo = new FileInfo(item);
                                if (fileInfo.LastWriteTime >= lastTime)
                                {
                                    maxCount--;
                                    return true;
                                }
                                return false;
                            }).ToList<string>();
            return fileList;
        }
        /// <summary>
        /// 查询目录下的所有文件,将recursive设为True可查询子目录中的所有文件。
        /// </summary>
        /// <param name="directory"></param>
        /// <param name="filePattern"></param>
        /// <param name="maxCount"></param>
        /// <param name="recursive"></param>
        /// <returns></returns>
        public static IList<FileInfo> FindFiles(string directory, string filePattern, int maxCount, bool recursive)
        {
            if (!recursive)
            {
                return FileHelper.FindFiles(directory, filePattern, maxCount);
            }
            IList<string> directories = EnumerateAllSubDirectories(directory);
            return FindFiles(directories,filePattern, maxCount);
        }
        public static IList<FileInfo> FindFiles(IList<string> directories,string filePattern, int maxCount)
        {
            List<FileInfo> files = new List<FileInfo>();
            foreach (string directoryItem in directories)
            {
                files.AddRange(FileHelper.FindFiles(directoryItem, filePattern, maxCount));
                if (files.Count > maxCount)
                {
                    break;
                }
            }
            return files.GetRange(0, Math.Min(files.Count, maxCount));
        }
        /// <summary>
        /// 默认查找20个文件
        /// </summary>
        /// <param name="directory"></param>
        /// <param name="filePattern"></param>
        /// <returns></returns>
        public static IList<FileInfo> FindFiles(string directory, string filePattern)
        {
            int maxCount = 20;
            return FindFiles(directory, filePattern, maxCount);
        }
        /// <summary>
        /// 获取文件
        /// </summary>
        /// <param name="directory"></param>
        /// <param name="filePattern"></param>
        /// <returns></returns>
        public static IList<FileInfo> FindFiles(string directory, string filePattern, int maxCount)
        {
            List<FileInfo> matchedFiles = new List<FileInfo>();
            IList<FileInfo> fileInfos = FindAllFiles(directory);
            if (string.IsNullOrWhiteSpace(filePattern))
            {
                return matchedFiles;
            }
            if (maxCount < 0 || maxCount > fileInfos.Count)
            {
                maxCount = fileInfos.Count;
            }
            maxCount--;
            foreach (var fileInfo in fileInfos)
            {
                if (maxCount <0)
                {
                    break;
                }
                if (FileHelper.IsMatched(fileInfo.Name, filePattern))
                {
                    matchedFiles.Add(fileInfo);
                }
                maxCount--;
            }
            return matchedFiles;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="directory"></param>
        /// <param name="filePattern"></param>
        /// <returns></returns>
        public static IList<FileInfo> FindAllFiles(string directory)
        {
            IList<FileInfo> fileInfos = new List<FileInfo>();
            if (string.IsNullOrWhiteSpace(directory))
            {
                return fileInfos;
            }
            if (!Directory.Exists(directory))
            {
                return fileInfos;
            }
            DirectoryInfo dir = new DirectoryInfo(directory);
            fileInfos = dir.GetFiles();
            return fileInfos;
        }
        /// <summary>
        /// 单个文件移动
        /// </summary>
        /// <param name="sourcePath"></param>
        /// <param name="targetDirectory"></param>
        /// <returns></returns>
        public static bool MoveFile(string sourcePath, string targetDirectory)
        {
            if (!File.Exists(sourcePath))
            {
                return false;
            }
            if (!Directory.Exists(targetDirectory))
            {
                return false;
            }
            var targetPath = string.Format("{0}\\{1}", targetDirectory, FileHelper.GetFileName(sourcePath));
            while (File.Exists(targetPath))
            {
                targetPath = FileHelper.Rename(targetPath);
            }
            if (sourcePath.Length > 260 || targetPath.Length > 260)
            {
                return MoveLongPathFile(@"\\?\"+sourcePath,@"\\?\"+ targetPath);
            }
            File.Move(sourcePath, targetPath);
            return true;
        }

[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "MoveFile")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool MoveLongPathFile(string lpExistingFileName, string lpNewFileName);
        /// <summary>
        /// 单个文件移动
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="sourceDirectory"></param>
        /// <param name="targetDirectory"></param>
        /// <returns></returns>
        public static bool MoveFile(string fileName, string sourceDirectory, string targetDirectory)
        {
            if (!File.Exists(fileName))
            {
                return false;
            }
            if (!Directory.Exists(sourceDirectory))
            {
                return false;
            }
            if (!Directory.Exists(targetDirectory))
            {
                return false;
            }
            string filePath = fileName.Replace(sourceDirectory, targetDirectory);
            string fileDir=Path.GetDirectoryName(filePath);
            if(!DirectoryHelper.CreateDirectory(fileDir))
            {
                return false;
            }
            return MoveFile(fileName, fileDir);
        }
        /// <summary>
        /// 重新生成新的文件路径
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string Rename(string filePath)
        {
            if (string.IsNullOrWhiteSpace(filePath))
            {
                return string.Empty;
            }
            string lastFileName = Path.GetFileNameWithoutExtension(filePath);
            string lastFileExtension = Path.GetExtension(filePath);
            //重命名,则随机在原来文件名后面加几个随机数字进行组装成新的名字
            Random random = new Random(System.DateTime.Now.Millisecond);
            string randomData = random.Next().ToString();
            //把原文件名的名字加上随机数,组装成新的文件名(避免重名)
            string newFileName = lastFileName + randomData;
            return Path.GetDirectoryName(filePath) + "\\" + newFileName + lastFileExtension;
        }

}
}

(0)

相关推荐

  • C#实现最完整的文件和目录操作类实例

    本文实例讲述了C#实现最完整的文件和目录操作类.分享给大家供大家参考.具体如下: using System; using System.Text; using System.IO; namespace HelloCsharp.Utilities { /// <summary> /// 文件操作类 /// </summary> public static class DirFile { #region 检测指定目录是否存在 /// <summary> /// 检测指定目录

  • C#实现的文件操作封装类完整实例【删除,移动,复制,重命名】

    本文实例讲述了C#实现的文件操作封装类.分享给大家供大家参考,具体如下: 最近发现群共享里面有个C# 文件操作封装类,其方法是调用Windows API 来操作的文件的删除.移动.复制.重命名操作.下载下来一试,发现果然不错,特在此记录,以防丢失! 文件操作类代码如下: using System; using System.Runtime.InteropServices; using System.IO; namespace LxFile { /// <summary> /// 文件操作代理,

  • C#实现用于操作wav声音文件的类实例

    本文实例讲述了C#实现用于操作wav声音文件的类.分享给大家供大家参考.具体如下: 有了这个C#类,我们可以很轻易的调用本地wav文件进行同步播放或者异步播放,大大简化了对wav文件的操作过程,如果你需要在项目中调用wav文件进行声音播放,可以使用这个C#类. using System; using System.Media; namespace DotNet.Utilities { /// <summary> /// 处理多媒体的公共类 /// </summary> public

  • C#的FileInfo类实现文件操作实例

    C#的FileInfo类提供了与File类相同的功能,不同的是FileInfo提供的都是成员方法,使用示例如下所示: 1.读文件: //创建只读 System.IO.FileStream. public System.IO.FileStream OpenRead() //创建使用 UTF8 编码.从现有文本文件中进行读取的 System.IO.StreamReader. public System.IO.StreamReader OpenText() 2.写文件: //创建只写 System.I

  • c#使用DotNetZip封装类操作zip文件(创建/读取/更新)实例

    下载地址在这里:http://dotnetzip.codeplex.com/ 下载到的包里有很多个dll文件,一般引用Ionic.Zip.dll就可以: 然后引用这个命名空间: using Ionic.Zip; 以下是我自己封装的一个类: 复制代码 代码如下: /// <summary>    /// Zip操作基于 DotNetZip 的封装    /// </summary>    public static class ZipUtils    {        /// <

  • C#的File类实现文件操作实例详解

    C#对文件的操作相当方便,主要涉及到四个类:File.FileInfo.Directory.DirectoryInfo,前两个提供了针对文件的操作,后两个提供了针对目录的操作,类图关系如下: 本文举例详述了File类的用法.File中提供了许多的静态方法,使用这些静态方法我们可以方便的对文件进行读写查等基本操作. 具体用法说明及相关示例如下: 1.读文件: // 打开一个文件,将文件的内容读入一个字符串,然后关闭该文件. public static byte[] ReadAllBytes(str

  • C#封装的常用文件操作类实例

    本文实例讲述了C#封装的常用文件操作类.分享给大家供大家参考.具体如下: 这个C#类封装了我们经常能用到的文件操作方法,包括读写文件.获取文件扩展名.复制文件.追加内容到文件.删除文件.移动文件.创建目录.递归删除文件及目录.列目录.列文件等,不可多得. using System; using System.Text; using System.Web; using System.IO; namespace DotNet.Utilities { public class FileOperate

  • c#保存窗口位置大小操作类(序列化和文件读写功能)

    记录窗口上次关闭的位置和大小 复制代码 代码如下: namespace PDSafe.Base{    public class Setting    {        ///<summary>        /// 把对象序列化为字节数组        ///</summary>        public static byte[] SerializeObject(object obj)        {            if (obj == null)         

  • C#中File类的文件操作方法详解

    本文实例讲述了C#中File类的文件操作方法.分享给大家供大家参考.具体分析如下: File类,是一个静态类,主要是来提供一些函数库用的.静态实用类,提供了很多静态的方法,支持对文件的基本操作,包括创建,拷贝,移动,删除和打开一个文件.File类方法的参量很多时候都是路径path.File的一些方法可以返回FileStream和StreamWriter的对象.可以和他们配套使用. System.IO.File类和System.IO.FileInfo类主要提供有关文件的各种操作,在使用时需要引用S

  • C#常用目录文件操作类实例

    本文实例讲述了C#常用目录文件操作类.分享给大家供大家参考.具体分析如下: 这个c#类封装了常用的目录操作,包括列出目录下的文件.检测目录是否存在.得到目录下的文件列表.检测目录是否为空.查找目录下的文件等等功能 using System; using System.Text; using System.IO; namespace DotNet.Utilities { /// <summary> /// 文件操作夹 /// </summary> public static clas

  • C#操作CSV文件类实例

    本文实例讲述了C#操作CSV文件类.分享给大家供大家参考.具体分析如下: 这个C#类用于转换DataTable为CSV文件.CSV文件转换成DataTable,如果需要进行CSV和DataTable之间进行转换,使用这个类非常合适. using System.Data; using System.IO; namespace DotNet.Utilities { /// <summary> /// CSV文件转换类 /// </summary> public static class

随机推荐