文件重命名(递归)

假设需要写入日志文件,但是不希望日志文件太大影响程序性能,这时需要将原文件重命名

//判断文件是否大于10M
            //取得文件大小
            if (File.Exists(logpath))
            {
                FileInfo MyFileInfo = new FileInfo(logpath);
                float MyFileSize = (float)MyFileInfo.Length / (1024 * 1024);
                if (MyFileSize > 10)
                {
                    //将原文件重命名
                    RenameLog(logpath);
                }
            }


        //递归重命名
        private static void RenameLog(string logpath)
        {
            string curPath = System.IO.Path.GetDirectoryName(logpath);//"d:\ffff\fwww"
            string curName = System.IO.Path.GetFileNameWithoutExtension(logpath);//errorlog.txt
            string curExt = System.IO.Path.GetExtension(logpath);//.txt

            // 新文件名
            int nextNum = 1;
            string newStr = "";
            try
            {
                //判断存不存在下一个文件,如果存在就递归
                nextNum = GetPathNum(logpath) + 1;
                newStr = curPath + "\\" + RemoveNum(curName) + "_" + nextNum + curExt;
                if (File.Exists(newStr))
                {
                    RenameLog(newStr);
                }
            }
            catch
            {
                newStr = curPath + "\\" + curName + "_" + Guid.NewGuid() + curExt;
            }

            // 改名方法
            FileInfo fi = new FileInfo(logpath);
            fi.MoveTo(Path.Combine(newStr));

        }
        private static int GetPathNum(string pathorname)
        {
            try
            {
                string curname = System.IO.Path.GetFileNameWithoutExtension(pathorname);
                if (!curname.Contains('_'))
                {
                    return 0;
                }
                return int.Parse(curname.Split('_')[curname.Split('_').Count() - 1]);

            }
            catch
            {
                return 0;
            }
        }
        //去除名称后的数字号
        private static string RemoveNum(string name)
        {
            try
            {
                if (!name.Contains('_'))
                {
                    return name;
                }
                return name.Substring(0, name.Length - (name.Split('_')[name.Split('_').Count() - 1].Length + 1));
            }
            catch
            { return name; }

        }

  效果:

 

转载于:https://www.cnblogs.com/King-JJ/p/6022671.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值