用C#.NET实现删除指定文件

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace DeleteFile
{
    class Program
    {
      public static void DeleteFile(string dirRoot)
      {
        string deleteFileName = "_desktop.ini";//要删除的文件名称
        try
        {
          string[] rootDirs = Directory.GetDirectories(dirRoot); //当前目录的子目录:
          string[] rootFiles = Directory.GetFiles(dirRoot);        //当前目录下的文件:

          foreach (string s2 in rootFiles)
          {
            if (s2.Contains(deleteFileName))
            {
              Console.WriteLine(s2);
              File.Delete(s2);                      //删除文件
            }
          }
          foreach (string s1 in rootDirs)
          {
            DeleteFile(s1);
          }
        }
        catch(Exception ex)
        {
          Console.WriteLine(ex.Message.ToString());
        }

      }
      static void Main(string[] args)
      {
        string[] drives = Directory.GetLogicalDrives();//系统所有根目录

        foreach (string s in drives)
        {
          DeleteFile(s);
        }
        Console.WriteLine("Delete Files Complete!");
        Console.ReadLine();
      }
    }
}


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/mane_yao/archive/2010/07/26/5765788.aspx

 

另一种方法:

 /// <summary>
        /// 删除指定文件夹,文件
        /// </summary>
        /// <param name="dir"></param>
        public static void DeleteFolder(string dir)
        {
            foreach (string d in Directory.GetFileSystemEntries(dir))
            {
                if (File.Exists(d))
                {
                    FileInfo fi = new FileInfo(d);
                    if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
                        fi.Attributes = FileAttributes.Normal;
                    File.Delete(d);//直接删除其中的文件  
                }
                else
                    DeleteFolder(d);//递归删除子文件夹  
            }
            Directory.Delete(dir);//删除已空文件夹  
        }

你可能感兴趣的:(.net)