Hi,
i am facing problem in
i have a project directory which contain some useful files and some waste files.
project directory hierarchy is as follows
Project directory
-- directory1
--- subdirectory with waste files
--- useful files
-- directory2
--- subdirectory with waste files
--- useful files
now i want to delete the directory by copying useful files out and then after recreating the directory ,i wish to copy the same files back to their hierarchy.
Can anybody send me code for this in c#.
regards

directory deletion adn recreation
Socrates Kapetaneas
crash33
I can't provide you the code as there are too many scenarios you need to decide how to answer. However I will provide you the general algorithm.
Firstly you need to decide what files to keep. For each of these files you can copy them to a temporary directory.
//Create a staging area to hold the files
string strPath = Path.Combine(Path.GetTempPath(), "BackupFiles");
Directory.Create(strPath);
foreach (string file in filesToKeep)
{
string destination = Path.Combine(strPath, Path.GetFileName(file));
File.Copy(file, destination, true);
}
Now that all files have been copied you can delete the directory.
Directory.Delete(directoryToDelete, true);
Directory.Create(directoryToDelete);
Finally copy the files back.
foreach (string file in Directory.GetFiles(strPath))
{
File.Copy(file, directoryToDelete, true);
}
Directory.Delete(strPath, true);
The above code skips over a lot of details. For example if security gets in the way then the code will fail. If an exception is thrown during the operation you might be left with copies of the original files. The list goes on. It also doesn't handle the issue of having files in subdirectories that you want to keep.
Personally I would recommend that you simply enumerate all files and subdirectories and if each file/directory doesn't meet some criteria then you delete it. You should probably wrap all calls for deletion in a try-catch block. You should also be aware that a file/directory may be temporarily locked after you perform any IO. Therefore I personally use a simple helper method that makes 5 or so attempts to delete a file/directory before actually failing the call.
bool DeleteFile ( string filePath )
{
for (int nIdx = 0; nIdx < 5; ++nIdx)
{
try
{
File.Delete(filePath, true);
return true;
} catch (FileException e) //Handling all file exceptions here but really should only handle those that matter
{ };
};
return false;
}
//Enumerate the files
foreach (string file in Directory.GetFiles(directoryToClean))
{
if (!ShouldDeleteFile(file))
if (!DeleteFile(file))
//Raise exception, report error, or whatever
};
//Enumerate the directories similarily
Michael Taylor - 8/1/06