1.11M Members

delete all files and folders in a directory but leave the directory

 
0
 

hi all
I want to write a visual C# programs that delete all files and folders in specific directory but leave the parents directory like
temp file
C:\Users\user\AppData\Local\Temp
MSN cache
C:\Users\user\AppData\Local\Microsoft\Windows Live\Contacts
etc etc...
but I need some help I had read the msdn library
http://msdn.microsoft.com/en-us/library/fxeahc5f.aspx
anyone could help me to write a program like that ?

 
0
 

Try this link. This one deals with working with files. Use this info to delete the files in the directory you want to keep. Use the other info you got to delete any subdirectories and their files in that directory.

 
0
 

@tinstaafl thanks man actcully I did it after posting that question as first step
here is what i have done

        private void Clear_Click(object sender, EventArgs e)
        {
            File.Delete("C:\\Users\\Samer\\Desktop\\1\\2.txt");
        }

and now i am trying to delete all files in the folder "1" using foreach.. just trying it
if anyone has anyother suggestion ?

 
0
 

here is what come up with... but that will delete the parant folder which named "1"
and I want to delete the contains of the folder "1" not the the folder it self

    private void Clear_Click(object sender, EventArgs e)
    {
        List<DirectoryInfo> FolderToClear = new List<DirectoryInfo>();
        FolderToClear.Add(new DirectoryInfo("C:\\Users\\Samer\\Desktop\\1\\"));

        foreach (DirectoryInfo directory in FolderToClear)
        {
            directory.Delete(true);
        }
    }
 
0
 

ForEach will work. use directory.getfiles to load an array with the fullpaths of all the files in a directory. then pass each string to files.delete

 
0
 

@tinstaafl ummmmm I made a list of directory in the code above as u can see
I think it will work better than array am I right ??
if you have ayn suggestion please Ill be glad to hear it :))

    private void Clear_Click(object sender, EventArgs e)
    {
        List<DirectoryInfo> FolderToClear = new List<DirectoryInfo>();

        // here is a list of files  I want to delete 
        FolderToClear.Add(new DirectoryInfo("path1"));
        FolderToClear.Add(new DirectoryInfo("path2"));
        FolderToClear.Add(new DirectoryInfo("path3"));
        FolderToClear.Add(new DirectoryInfo("path4"));

        foreach (DirectoryInfo directory in FolderToClear)
        {
            directory.Delete(true);
        }
    }

And Any ideas how to deal with the FileNotFoundException ????
anyother exceptions could come into ur mind ?

 
0
 

here is the last update of my code I had add some new ideas like the numbers of deleted files and I am working on The total size of it

and please if anyone could help me with these Issues I had post
how to delete everything that folder "1" contains but leave the folder it self ??
And Any ideas how to deal with the FileNotFoundException ????
anyother exceptions could come into ur mind ?

        public void clear_button()
        {
            try
            {
                int FilesCounter = 0;

                List<DirectoryInfo> FolderToClear = new List<DirectoryInfo>();
                FolderToClear.Add(new DirectoryInfo(@"C:\\Users\\user\\Desktop\\1\\"));

                foreach (DirectoryInfo directory in FolderToClear)
                {               
                    directory.Delete(true);
                    FilesCounter++;
                }


                MessageBox.Show("Done" + "\nDeleted Files Number is " + FilesCounter, "Message",);
                //Application.Exit();
            }
            catch
            {
                throw new FileNotFoundException();
            }
        }

Thanks all & goodnight for me now.....

 
0
 

I looked at the documentation for 'directoryinfo' and it indicates that your code will delete only the directories. I've put together a small routine that will do what you asked:

        private void DeleteContents(string Path)
        {
            string[] DirectoryList = Directory.GetDirectories(Path);
            string[] FileList = Directory.GetFiles(Path);

            foreach (string Fil in FileList)
            {
                File.Delete(Fil);
            }
            foreach ( string Drectory in DirectoryList)
            {
                Directory.Delete(Drectory, true);
            }
            MessageBox.Show("Done\nFiles deleted - " + FileList.Length + "\nDirectories deleted - " + DirectoryList.Length,"Results", MessageBoxButtons.OK);
        }

As for any notfound exceptions, since you're deleting stuff anyway, just catch and ignore. One option if you don't want to use try-catch, you can read the .exist method for file/directory before your delete it. However your reading the directory and deleting the contents right away, there shouldn't be much chance of a file or directory being deleted or renamed before you try and do it.

 
0
 

Here's a try-catch block you can try if you want:

            try
            {
            }
            catch(Exception e)
            {
                if (e.Message.Contains("NotFound")) { }
                else
                    throw (e);
            }

This will ignore anything notfound and thorw anything(i.e. no permission)

 
0
 

@tinstaafl thanks for help first then

for the exception you suggest it do the same as the one did above...

the FileList.Length and DirectoryList.Length it gives an negative values like -5 etc...
so I declared two varabile as the code I show you before and add them to foreach loops
and the give me same result as the one in ur code but NOT negative is it wrong way ?

I nocited that if the flolder "1" has subfolder "2" and this folder contains files it will not be counted with the both way ur way and my way of counting files... ummm anyway u suggest to solve this ??

Thanks for help :)

   public void clear_button()
        {
            try
            {
                int FilesCounter = 0;
                int FoldersCounter = 0;

                string[] DirectoryList = Directory.GetDirectories("C:\\Users\\user\\Desktop\\1");
                string[] FileList = Directory.GetFiles("C:\\Users\\user\\Desktop\\1");

                foreach (string x in FileList)
                {
                    File.Delete(x);
                    FilesCounter++;
                }

                foreach (string y in DirectoryList)
                {
                    Directory.Delete(y, true);
                    FoldersCounter++;
                }

                MessageBox.Show("Done... ^_^\nFiles deleted - " + FileList.Length + "\nDirectories deleted - " + DirectoryList.Length +"\n"+FilesCounter+"\n"+FoldersCounter, "Results", MessageBoxButtons.OK,MessageBoxIcon.Information);
                Application.Exit();
            }
            catch (Exception SJD)
            {
                if (SJD.Message.Contains("NotFound"))
                {
                    MessageBox.Show("File Not Found");
                }
                else
                {
                    throw (SJD);
                }
                //throw new FileNotFoundException();
            }
        }
 
0
 

I made this method that calculate the total size of deleted files but I am getting this error msg

"Property or indexer 'System.IO.FileInfo.Length' cannot be assigned to -- it is read only"

its works fine when I code it in the same method clear_button above but its shows the message box in each loop and I did find away to get out of this problem

        public void File_Size()
        {
            //File Size
            int TotalFileSize;
            DirectoryInfo X = new DirectoryInfo("C:\\Users\\Samer\\Desktop\\1");
            FileInfo[] FileSize = X.GetFiles();
            foreach (FileInfo Finfo in FileSize)
            {
                Finfo.Length = TotalFileSize;
            }
        }
 
1
 

Finfo can only be read. You cannot set it's Length property. I guess you mean to do this:

        public int File_Size()
        {
            int TotalFileSize = 0;
            DirectoryInfo X = new DirectoryInfo("C:\\Users\\Samer\\Desktop\\1");
            FileInfo[] FileSize = X.GetFiles();
            foreach (FileInfo Finfo in FileSize)
            {
                TotalFileSize += Finfo.Length;
            }
            return TotalFileSize;
        }
 
0
 

I don't know how you got negative values on the length property, it should be either 0 or positive integer. Also in your catch routine, your exception wil also catch directorynotfound, if others are going to using this you might want to include that possibility in your message. One way to count all the files and sub directories is to use the directorylist and loop through it and count the files in each directory. You can nest another foreach loop to count the files before you delete the directories.

 
0
 

the whole code in your hands man me too i dont know How I get negative values..
ummmm and yea other may use this code and now I am afriad if I want to add new directories to other program is really not efficient way to add each path for each program/path or I forget to add one of path to all these part of code
for example i want to add new path so i should add the path in

1 DirectoryList
2 FileList
3 to File_Size method

is there is any better ways to do this ??

I am thinking to add a textbox and add path button to allow other to add new paths
is that possible ??
or add feadback button that send an email to my email ...

i dont know any ideas ??

Thanks all for help
thanks pritaeas

 
0
 

I would suggest calling the delete routine with one path at a time. But you can set it up for user input with, A button, a label, and a folderbrowserdialog. in the button click event call the dialog, use the label to display the path, then display a messagebox to confirm, since you'll be making massive deletes. Then either call the delete sub with the path(separate variable or use label.text) as a parameter or have another button to call it and get the path from the label.text. If you really want to do multiple paths at once, storing the paths in a textbox, make it read-only, and using an add button will work, but I would still suggest having the add button call the folderbrowserdialog, as that way you know for certain that you'll be getting valid path strings. You might want an edit button to delete a path from the textbox. and maybe an option(radio button?) to confirm each path before delete or not. and of course the delete paths button.

 
0
 

@tinstaafl thats what ill try to do and you suggest to call the delete routine with one path at a time how cloud i do that ??
at the beganing i made a list so I call it one time but now with the modification and developing the code I cant use list

 
0
 

If you look at the routine I posted originally, it excepts a path variable as string(i.e private void DeleteContents(string Path)). In the subroutine,Path holds the path to the directory you want to empty. In your click event, to call the subroutine use DeleteContents(label1.text). If you still want to use a list, get it set up to do one path at a time. if your list is never, or infrequently changed you can put it into an array and loop through the array in the button click event. If the list changes with each user, or each time the program is called, my previous suggestion with the textbox will work the same way, except textbox already has an array its textbox.lines, and you can loop through it the same way.

 
0
 

@tinstaafl uh ill try it and ill replay back to u
and here is what I have done about adding new path to the code but that code delete the file instantly when I click on the button and it one time use what I actlly want to do is add this path to the code it self so could be use again and again ... got it ??
if yes how is that possible ?

i thnik in ajax where able to something like that but c# I have no idea if that possible

        private void Browse_Click(object sender, EventArgs e)
        {
            OpenFileDialog browseButton = new OpenFileDialog();

            browseButton.InitialDirectory = "c:\\";

            if (browseButton.ShowDialog() == DialogResult.OK)
            {
                DialogResult DR;
                DR = MessageBox.Show("You are going to add " + browseButton.FileName + " path to delete list.\nAre you sure?", "Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                BrowseTextBox.Text = browseButton.FileName;
                if (DialogResult == DialogResult.OK)
                {
                    // add the path to the code ??
                }
            }
        }
 
0
 

first off you're using the openfiledialog, which will point to a file, which will require parsing it to get the path to the file. If you use the folderbrowserdialog it will point only to the folder path, not requiring any parsing. Here's the way I did it:

            private void button1_Click(object sender, EventArgs e)
            {
                folderBrowserDialog1.RootFolder=Environment.SpecialFolder.MyComputer;
                folderBrowserDialog1.SelectedPath = "C:\\";            
                DialogResult Result= folderBrowserDialog1.ShowDialog();
                if (Result != DialogResult.Cancel)
                {
                    label1.Text = folderBrowserDialog1.SelectedPath;
                    Result= MessageBox.Show("Do you want to delete the contents of theis folder?", "Confirm Delete", MessageBoxButtons.YesNo);
                    if (Result != DialogResult.No)
                    {
                        DeleteContents(label1.Text);
                    }
                    else
                    {
                        label1.text="";
                    }
                }
            }
            private void DeleteContents(string Path)
            {
                string[] DirectoryList = Directory.GetDirectories(Path);
                string[] FileList = Directory.GetFiles(Path);
                foreach (string Fil in FileList)
                {
                    File.Delete(Fil);
                }
                foreach ( string Drectory in DirectoryList)
                {
                    Directory.Delete(Drectory, true);
                }
                MessageBox.Show("Done\nFiles deleted - " + FileList.Length + "\nDirectories deleted - " + DirectoryList.Length,"Results", MessageBoxButtons.OK);
            }               
 
0
 

Did some looking, found how to get total number of files and total number of directories:

int AllFiles = Directory.GetFiles(Path, "*", SearchOption.AllDirectories).Length;
int AllDirs = Directory.GetDirectories(Path, "*", SearchOption.AllDirectories).Length;

this reports exctly the same info you get when the properties for a folder, reports the number of files and folders.

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article