删除本地文件方法

using HY.Service.Config;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Demon01
{
    public partial class Form1 : Form
    {
        private static string logContent;

        public Form1()
        {
            InitializeComponent();
        }


        /// <summary>
        /// 云盘删除操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {

            Console.ReadLine();
            string selectPath = @"\\192.168.0.0\备份盘";
            GetFiles(selectPath, 5);
            Console.WriteLine("测试一下!");

        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="path">\\192.168.1.114\资料备份路径</param>
        /// <param name="retainCount"></param>
        private void GetFiles(string path, int retainCount)
        {

            string demon = @"\\127.0.01\备份盘\1.txt";
            using (Process myPro = new Process())
            {
                myPro.StartInfo.FileName = "cmd.exe";
                myPro.StartInfo.UseShellExecute = false;
                myPro.StartInfo.RedirectStandardInput = true;
                myPro.StartInfo.RedirectStandardOutput = true;
                myPro.StartInfo.RedirectStandardError = true;
                myPro.StartInfo.CreateNoWindow = true;
                myPro.Start();
                string cmdStr = "dir " + path + "/s/b>" + demon;
                myPro.StandardInput.WriteLine(cmdStr);
                myPro.StandardInput.AutoFlush = true;
                myPro.WaitForExit();
            }







            //要删除的目录信息
            //var dicInfo = new DirectoryInfo(path);//选择的目录信息  
            //DirectoryInfo[] dic = dicInfo.GetDirectories("*.*", SearchOption.TopDirectoryOnly);
            //foreach (DirectoryInfo temp in dic)
            //{
            //    try
            //    {
            //        if (temp.FullName.Length < 240)
            //        {
            //            GetFiles(temp.FullName, retainCount);
            //        }
            //    }
            //    catch (Exception ex)
            //    {
            //        logContent = "删除云盘异常文件:" + path + ";异常信息:" + ex.Message;
            //        WriteLog(logContent, true);
            //    }
            //}
            //List<FileInfoModel> fileNameList = new List<FileInfoModel>();
            //FileInfo[] textFiles = dicInfo.GetFiles("*.*", SearchOption.TopDirectoryOnly);//获取所有目录包含子目录下的文件  
            //foreach (FileInfo temp in textFiles)
            //{
            //    fileNameList.Add(GetFileInfo(temp.FullName));
            //}
            //DeleteFileList(fileNameList, retainCount);

            ////要删除的目录信息
            //var dicInfo = new DirectoryInfo(path);//选择的目录信息  

            DateTime data1 = DateTime.Now;
            List<string> list = new List<string> { path, retainCount.ToString() };
            //ParameterizedThreadStart这是一个参数类型为object的委托
            ParameterizedThreadStart pts = new ParameterizedThreadStart(SayHello);
            Thread td2 = new Thread(pts);
            td2.Start(list);  //参数值先入这里

            List<string> list_t = new List<string> { path, retainCount.ToString() };
            //ParameterizedThreadStart这是一个参数类型为object的委托
            ParameterizedThreadStart pts1 = new ParameterizedThreadStart(SayHello_two);
            Thread td1 = new Thread(pts1);
            td1.Start(list_t);  //参数值先入这里
            DateTime data2 = DateTime.Now;
            TimeSpan ts = data2 - data1;
        }



        /// <summary>
        /// 线程执行
        /// </summary>
        /// <param name="list"></param>
        void SayHello(object list)
        {
            List<string> lts = list as List<string>;
            //要删除的目录信息
            var dicInfo = new DirectoryInfo(lts[0]);//选择的目录信息  
            DirectoryInfo[] dic = dicInfo.GetDirectories("*.*", SearchOption.TopDirectoryOnly);
            foreach (DirectoryInfo temp in dic)
            {
                try
                {
                    if (temp.FullName.Length < 240)
                    {
                        GetFiles(temp.FullName, int.Parse(lts[1]));
                    }
                }
                catch (Exception ex)
                {
                    //logContent = "删除云盘异常文件:" + lts[0] + ";异常信息:" + ex.Message;
                    //WriteLog(logContent, true);
                }
            }
        }
        /// <summary>
        /// 线程执行
        /// </summary>
        /// <param name="list"></param>
        void SayHello_two(object list)
        {
            List<string> lt = list as List<string>;
            //要删除的目录信息
            var dicInfo = new DirectoryInfo(lt[0]);//选择的目录信息  
            FileInfo[] textFiles = dicInfo.GetFiles("*.*", SearchOption.TopDirectoryOnly);//获取所有目录包含子目录下的文件  
            List<FileInfoModel> fileNameList = new List<FileInfoModel>();
         
            foreach (FileInfo temp in textFiles)
            {
                fileNameList.Add(GetFileInfo(temp.FullName));
            }
            if (fileNameList.Count > 0)
            {
                //寻找要删除的文件以及参数5
                DeleteFileList(fileNameList,int.Parse(lt[1]));
            }

        }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="str"></param>
        /// <param name="logType"></param>
        static void WriteLog(string str, bool isError)
        {
            if (!Directory.Exists("Log"))
            {
                Directory.CreateDirectory("Log");
            }
            string path = isError ? @"Log\ErrLog.txt" : @"Log\CommonLog.txt";
            using (var sw = new StreamWriter(path, true))
            {
                sw.WriteLine(System.DateTime.Now + "  " + str);
                sw.WriteLine("---------------------------------------------------------");
                sw.Close();
            }
        }


        public static FileInfoModel GetFileInfo(string fileFullName)
        {
            FileInfoModel item = new FileInfoModel();
            try
            {
                string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(fileFullName);
                item.FullFileName = fileFullName;
                item.FileExtension = System.IO.Path.GetExtension(fileFullName);
                item.SplitChar = '_';
                int charIndexOf = fileNameWithoutExtension.LastIndexOf(item.SplitChar);
                if (charIndexOf > 0)
                {
                    string strIndex = fileNameWithoutExtension.Substring(charIndexOf + 1, fileNameWithoutExtension.Length - (charIndexOf + 1));
                    item.Index = CustomConvertToInt(strIndex, 1);
                    item.FileNameWithoutIndex = fileNameWithoutExtension.Substring(0, charIndexOf);
                }
                else
                {
                    item.Index = 0;
                    item.FileNameWithoutIndex = fileNameWithoutExtension;
                }
            }
            catch (Exception ex)
            {
                //logContent = "获取文件" + fileFullName + "信息出错:" + ex.Message;
                //WriteLog(logContent, true);
            }
            return item;
        }
        /// <summary>
        /// 将value值转为int 否则传出5
        /// </summary>
        /// <param name="value"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        private static int CustomConvertToInt(string value, int defaultValue)
        {
            int result = defaultValue;
            try
            {
                result = Convert.ToInt32(value);
            }
            catch
            {
                result = defaultValue;
            }
            return result;
        }



        private static void DeleteFileList(List<FileInfoModel> fileList, int retainCount)
        {
            if (fileList == null || fileList.Count == 0)
            {
                return;
            }
            fileList.ForEach(p => {
                //查询文件中带@符号的文件
                int charIndexOf = p.FileNameWithoutIndex.LastIndexOf('@');
                //查找名称长度大于10的
                if (charIndexOf > 0 && p.FileNameWithoutIndex.Substring(charIndexOf + 1).Length > 10)
                    p.delete = true;
            });
            var groupList = fileList.GroupBy(m => m.FileNameWithoutIndex).ToList();
            foreach (var group in groupList)
            {
                var groupFileList = group.OrderBy(m => m.Index).ToList();
                if (retainCount < groupFileList.Count)
                {
                    for (int i = groupFileList.Count - retainCount; i > 0; i--)
                    {
                        groupFileList[i].delete = true;
                    }
                }

                string filePath = string.Empty;
                if (groupFileList != null && groupFileList.Count > 0)
                {
                    filePath = System.IO.Path.GetDirectoryName(groupFileList[0].FullFileName);
                    var deleteList = groupFileList.Where(m => m.delete).ToList();
                    var retainList = groupFileList.Where(m => m.delete == false).ToList();
                    DeleteFile(filePath, deleteList, retainCount);
                    ReNameFile(filePath, retainList);
                }
            }
        }

        /// <summary>
        /// 删除文件夹
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="deleteList"></param>
        /// <param name="retainCount"></param>
        /// <returns></returns>
        public static bool DeleteFile(string filePath, List<FileInfoModel> deleteList, int retainCount)
        {
            int delereCount = 0;
            foreach (var deleteItem in deleteList)
            {
                try
                {
                    System.IO.File.Delete(deleteItem.FullFileName);
                    //WriteLog("删除文件" + deleteItem.FullFileName, false);
                    delereCount++;
                }
                catch (Exception ex)
                {
                    //logContent = "删除文件失败:" + ex.Message;
                    //WriteLog(logContent, true);
                }
            }
            //WriteLog("文件夹" + filePath + "删除文件数" + delereCount, false);
            return true;
        }
        /// <summary>
        /// 重命名文件夹
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="retainList"></param>
        /// <returns></returns>
        public static bool ReNameFile(string filePath, List<FileInfoModel> retainList)
        {
            for (int i = 0; i < retainList.Count; i++)
            {
                try
                {
                    string oldFileName = retainList[i].FullFileName;
                    string newFileName = filePath + @"\" + retainList[i].FileNameWithoutIndex;
                    if (i == 0)
                    {
                        newFileName += retainList[i].FileExtension;
                    }
                    else
                    {
                        newFileName += retainList[i].SplitChar.ToString() + i.ToString() + retainList[i].FileExtension;
                    }
                    System.IO.File.Move(oldFileName, newFileName);
                }
                catch (Exception ex)
                {
                    //logContent = "重命名文件失败:" + ex.Message;
                    //WriteLog(logContent, true);
                }
            }
            return true;
        }
    }
}

 

转载于:https://www.cnblogs.com/SDdemon/p/11138742.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值