MikeTech
MikeTech

Reputation: 1

Deleting a specific folder and it's files ASP.NET

Alright so I'm having a bit of an issue here. I'm trying to delete a specific folder inside another folder on my webserver using ASP.NET (C#) The folder being deleted is based on a textbox.

The directory is like this

/images/folderx

folderx = txtDelFolder.Text;

The problem is that everything I try deletes every single thing inside the images folder. I'm guessing that it is not recognizing my folder in the filepath

string path = @"\httpdocs\images\ + txtDelFolder.Text;

I have also tried

string path = @"\httpdocs\images\ + txtDelFolder.Text + "\";

Tried all this with both single '\' and double '\'

Would appreciate any help on this

Also where it says <directfilepath> I actually have the filepath typed out, just didn't want to share that here.

****edit****

string path = Server.MapPath("~/imagestest/" + txtEditTitle.Text);

  if(Directory.Exists(path)) 
  { 
  DeleteDirectory(path); 
  } 
 } 
} 
private void DeleteDirectory(string path) 
{ 
 foreach(string filename in Directory.GetFiles(path)) 
 { 
 File.Delete(filename); 
 } 
 foreach(string subfolders in Directory.GetDirectories(path)) 
 { 
 Directory.Delete(subfolders, true); 
 } 
}

Upvotes: 0

Views: 9220

Answers (3)

NickSuperb
NickSuperb

Reputation: 1204

Don't see why this wouldn't work:

public static bool DeleteDirectory(string input)
{
    if (Directory.Exists(input))
    {
        Directory.Delete(input, true);
        return !Directory.Exists(input);
    }
    else
        return true;
}

string thePath = Server.MapPath(@"~/images/");
thePath = Path.Combine(Path.GetFullPath(thePath), txtInput.Text);

if(DeleteDirectory(thePath))
    Console.WriteLine("YAY");
else
    Console.WriteLine("BOO");

Upvotes: 0

Lamourou abdallah
Lamourou abdallah

Reputation: 354

try this one :

public void DeleteFolder(string folderPath)
    {
        if (!Directory.Exists(folderPath))
            return;
        // get the directory with the specific name
        DirectoryInfo dir = new DirectoryInfo(folderPath);
        try
        {
            foreach (FileInfo fi in dir.GetFiles())
                fi.Delete();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

Upvotes: 0

malkam
malkam

Reputation: 2355

Try this:

private void DeleteFiles(string folder)
        {
            string path=Server.MapPath("~/httpdocs/images/" + folder);
            string[] files=Directory.GetFiles(path, "*", SearchOption.AllDirectories);
            foreach (string file in files)
            {
                File.Delete(file);
            }
             //then delete folder
              Directory.Delete(path);

        }

Upvotes: 2

Related Questions