chh
chh

Reputation:

How to replace a directory with the same name with new one?

I am putting a check that if a directory by a name exists then it should delete that directory and replace it with the new one. For that i am having this code:

if (Directory.Exists(b))
{
    Directory.Delete(b);
    Directory.CreateDirectory(b);
}

where b is the name of the directory for which i am outting the check. I am getting a run time error that Directory is not empry, what shall i do?

Upvotes: 1

Views: 3951

Answers (4)

Ole Lynge
Ole Lynge

Reputation: 4587

Delete subdirectories and files by setting a second boolean parameter to true:


if (Directory.Exists(b))
{
    Directory.Delete(b, true);
    Directory.CreateDirectory(b);
}

Upvotes: 2

Daniel Brückner
Daniel Brückner

Reputation: 59705

You must call Directory.Delete(path, true) to force the deletion of subdirectories and files.

Upvotes: 2

ChrisF
ChrisF

Reputation: 137188

If the directory isn't empty you'll need to go in enumerate all the files and delete those first.

You'll also have to recurse down any subfolders too.

Or just call Directory.Delete(folder, true) of course!

Upvotes: 2

trendl
trendl

Reputation: 1147

Try Directory.Delete(b, true)

Upvotes: 5

Related Questions