zoukankan      html  css  js  c++  java
  • 删除本地文件方法

    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 ? @"LogErrLog.txt" : @"LogCommonLog.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;
            }
        }
    }
  • 相关阅读:
    Jzoj4729 道路修建
    Jzoj4727 挺进
    Jzoj4727 挺进
    Jzoj4726 种花
    Jzoj4726 种花
    Jzoj4725 素数序列
    Jzoj4725 素数序列
    力扣算法题—040组合求和二
    力扣算法题—039组合求和
    力扣算法题—038报数
  • 原文地址:https://www.cnblogs.com/SDdemon/p/11138742.html
Copyright © 2011-2022 走看看