65.9K
CodeProject is changing. Read more.
Home

CleanUp Files using C Sharp

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.27/5 (9 votes)

Jan 23, 2001

viewsIcon

90963

downloadIcon

903

Describes the File Access, Persistance with C Sharp

  • Download source files - 35 Kb
  • Introduction

    This article is just a sample application which uses the .Net framework to delete unwanted files from the directories specified. The Sample uses the System.IO to manage the task and uses a recursive function to delete files.

    private void RemoveFiles(string strPath)
    {
        Directory dTemp = new Directory(strPath);
        for(int i = 0; i < lstExts.Items.Count; i++)
        {
            string s = lstExts.Items[i].ToString();
            File[] fileList = dTemp.GetFiles(lstExts.Items[i].ToString());
            for(int j = 0; j < fileList.Length; j++)
            {
                if(fileList[j].IsFile)
                {
                    try
                    {
                        fileList[j].Delete();    
                    } 
                    catch(SecurityException e)
                    {
                        lblStatus.Text = e.Message;
                    }
                    catch(Exception ex)
                    {
                        lblStatus.Text = ex.Message;
                    }
                }
            }
        }
    }
    
    private void EmptyDirectory(string strPath)
    {
        if(!Directory.DirectoryExists(strPath))
            return;
        Directory dirFinder = new Directory(strPath);
        Directory[] dirList = dirFinder.GetDirectories();    
        for(int i = 0; i < dirList.Length; i++)
        {
            string strTemp = strPath + "\\" + dirList[i].Name;
            EmptyDirectory(strTemp);
            RemoveFiles(strTemp);
        }
        RemoveFiles(strPath);
    }
    
    

    The two functions provides the capability of deleting of files recursively. The Classes used in this Project

    • Form
    • File
    • Directory
    • Button
    • ListBox
    • TextBox