Expiring Today—Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Problem with deleting directories under C#

Posted on 2008-10-22
9
Medium Priority
?
445 Views
Last Modified: 2013-12-17
Hi there;

I got a question that in VS. 2008 i wrote a code to delete desktop and d:\ drive...

The problem is i want to exclude some dirs...For example "Recycler" for D: drive...

String[] dirs= Directory.GetDirectories("d:\\RECYCLER"); i have to use...But it fails...
Then iterate under for and delete the dirs if the dirname is not Recycler...That's it but i failed doing that no file/folder is deleted when i try for that...

I want to modify the below code that when the program is executed, the RECYCLER is preserved and not deleted...Other than that will be deleted...

Best regards...


internal void DeleteContentDirectories()
        {
            try
            {
                //Console.WriteLine("asdf" + _currentUserDirectoryProvider.UserDirectory + "1234");
                Directory.Delete("C:\\Documents and Settings\\" + _currentUserDirectoryProvider.UserDirectory + "\\Desktop",true);
               //Directory.CreateDirectory("C:\\Documents and Settings\\" + _currentUserDirectoryProvider.UserDirectory + "\\Desktop");
                //Directory.Delete("f:", true);
                //Directory.Delete("C:\\Documents and Settings\\" + _currentUserDirectoryProvider.UserDirectory + "\\Desktop", true);
                Directory.Delete("d:", true);
                 //+ _currentUserDirectoryProvider.UserDirectory);
            }
            catch (Exception e)
            {
            }
        }

Open in new window

0
Comment
Question by:jazzIIIlove
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
9 Comments
 
LVL 1

Assisted Solution

by:MarkMyburgh
MarkMyburgh earned 2000 total points
ID: 22775252
Hi
you could just loop through the directories on D and make sure the name is not Recycle.  or have a look at the info.attibutes.  you might now want to delete a directory if it is system.
below is a code example;
regards
Mark

    var directories = Directory.GetDirectories("d:");
                foreach (string dir in directories)
                {
                    DirectoryInfo info = new DirectoryInfo(dir);
                    if (info.Name != "RECYCLER")
                    {
                        Directory.Delete(dir, true);
                    }
                }

Open in new window

0
 
LVL 12

Author Comment

by:jazzIIIlove
ID: 22831435
Hi there;
Thank you for your snippet...

the thing is the program deletes the CONTENT of desktop and D: drive...A cleaner program that deletes the students things...I have no problem with deleting D: but for desktop, i have some...When i delete the desktop in a recursive manner, i delete not only the content but the desktop folder itself...I don't want this...just deleting the things in desktop except recycler, my computer (I cannot find them in C:\Doc.Set\stu_id\Desktop)
I can get the stu_id without a glitch so that i can reach his/her desktop...But when i say delete it recursively, he deletes not only content but also desktop folder itself...I want it delete inside of it/content and exclude My Computer and Recycler...(What are their paths is another question here)

Thanks for your interest...

P.S. You may say delete the desktop, you will recreate it...Well no, because the machines are under domain and it has own rules...When i say recreate desktop, the program finishes the policy set to the machine...
0
 
LVL 1

Assisted Solution

by:MarkMyburgh
MarkMyburgh earned 2000 total points
ID: 22833056
hmm do you need to delete the files and the diretory ?
heres a snippet to remove files

void RemoveFiles(string path)
        {
            var directories = Directory.GetDirectories(path);
            foreach (var directory in directories)
            {
                foreach (var file in Directory.GetFiles(directory))
                {
                    try
                    {
                        File.Delete(file);
                    }
                    catch (FieldAccessException accex)
                    {
 
                    }
                    catch (FileNotFoundException notfoundex)
                    {
 
                    }
                    catch (Exception ex)
                    {
 
                    }
                }
                if (Directory.GetDirectories(directory).Length != 0)
                {
                    RemoveFiles(directory);
                }
            }            
        }

Open in new window

0
Veeam Task Manager for Hyper-V

Task Manager for Hyper-V provides critical information that allows you to monitor Hyper-V performance by displaying real-time views of CPU and memory at the individual VM-level, so you can quickly identify which VMs are using host resources.

 
LVL 12

Author Comment

by:jazzIIIlove
ID: 22833699
Hi there;

Thanks for your effort...To clarify:

<<hmm do you need to delete the files and the diretory

i want to delete the files and directory under desktop except for mycomputer and recycle bin...The desktop directory must stay only with recyclebin and mycomputer, other files and dirs must be purged inside desktop dir...

Also, i am deleting the D: drive (but here not a issue, i can delete d: drive content cooly)...

Best regards...
0
 
LVL 1

Accepted Solution

by:
MarkMyburgh earned 2000 total points
ID: 22834901
hmmm loop through the directory structure and if you find the folders you want to keep then do the removefile method else delete the directory.  However you might want to look if there is sub directories.  
you could implement a structure class that you look throught the directories first.
structure would look lke code snippet.
so loop through the directories on c and add a DirDelete structure to a collection.
something like collection<DirDelete> Dirs = new collection<DirDelete>;
loop:
  //check if delete dirictory
  DirDelete dir = new DirDelete();
  dir.DirPath = path;
  dir.action = RemoveDir
  Dirs.Add(dir);
//check if delete files
  DirDelete dir = new DirDelete();
  dir.DirPath = path;
  dir.action = RemoveFiles
  Dirs.Add(dir);

after looping though the coillection afterwoods and perform the action on the dir.

hope this makes senses.  i've had a really rough day and the mind is mash petatoes!

struct DirDelete
{
  string DirPath { get; set; }
  actiontype action ( get; set; }
  enum ActionType
{
  RemoveFiles
  RemoveDir
}
 
}

Open in new window

0
 
LVL 12

Author Comment

by:jazzIIIlove
ID: 22835072
again a nice effort but i am reluctant to write new struct or class to handle this problem of mine...Because timing is very important in this program...The program must finish within 15 seconds at most...So, adding a struct will be a bottleneck as i presume...

Best regards...
0
 
LVL 12

Author Comment

by:jazzIIIlove
ID: 22836512
Hi there;

by the way, i cannot find the path of RecycleBin and MyComputer under Doc. Sett.

I asked the question but i don't know how to adapt the following information to my code...

http://www.experts-exchange.com/OS/Microsoft_Operating_Systems/Windows/XP/Q_23859566.html

Best regards...and thanks for your patience and effort...
0
 
LVL 12

Author Closing Comment

by:jazzIIIlove
ID: 31508684
I used your code for a unit test and works perfectly fast indeed...So struct is not that bad solution for me...Thanks of your very effort and sorry for my delay...I was away...
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…

718 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question