Click to See Complete Forum and Search --> : Best way to create directory and file and copy file to file if it doesn't exist


ireland
April 10th, 2007, 07:51 AM
What's the best way to copy one file to another if the directories may not already exist and the file may not already exist?

Presently I'm checking for the parent folders existence, if they don't exist then create. Then check for the file's existence it it doesn't exist first delete it and then create and finally copy the original file to the new one..

if(!Directory.Exists(vsProjTemplateLoc))
Directory.CreateDirectory(vsProjTemplateLoc);
if (!Directory.Exists(Path.Combine(vsProjTemplateLoc, "Windows")))
Directory.CreateDirectory(Path.Combine(vsProjTemplateLoc, "Windows"));

string filePath = string.Empty;
if (File.Exists(filePath = Path.Combine(vsProjTemplateLoc, Path.Combine("Windows", templateFile))))
File.Delete(filePath);
File.Create(filePath).Close();
File.Copy(Path.Combine(originalLoc, templateFile), filePath, true);

Shuja Ali
April 10th, 2007, 08:49 AM
If you are creating a new folder then there is no need to check for the existence of the File. And to copy a file you don't need to create the file first. Just copy the file, thats it.

ireland
April 10th, 2007, 10:42 AM
Sure Shuja, no shortcuts then, that's fine.
Cheers,
LP.