欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-25 11:10:52
复制代码 代码如下:using system;using system.collections.generic;using system.io;using system.t...

复制代码 代码如下:

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;
        }

    }
}