Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

CleanUp Files using C Sharp

0.00/5 (No votes)
22 Jan 2001 1  
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

    License

    This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

    A list of licenses authors might use can be found here