-1

I want to delete a zip folder if it is exists. I have below code.

string zippath = @"C:\Neenu\Downloads.zip";
ZipFile.CreateFromDirectory(@"" + TemporaryFolder, @"" + zippath);

Just before the above code I want to check if folder exists or not. If exists I want to delete folder.

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • Take a look at the functions in System.IO.Directory – middelpat Mar 23 '17 at 10:34
  • [Directory.Exists](https://msdn.microsoft.com/en-us/library/system.io.directory.exists%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396) – stuartd Mar 23 '17 at 10:34
  • No File.Exists. Mind that a zip folder is just an ordinary file. – Willem Van Onsem Mar 23 '17 at 10:34
  • Which folder do you want to check? `TemporaryFolder`? Folder in zip-archive (though you create new, not adding)? It's not clear what you want to achieve, can you give us a better example/explanation of the problem? – Sinatr Mar 23 '17 at 10:37
  • I want to delete Downloads.zip – Neenu Surendran K Mar 23 '17 at 10:41
  • Possible duplicate of [How to delete a file after checking whether it exists](http://stackoverflow.com/questions/6391711/how-to-delete-a-file-after-checking-whether-it-exists) – user247702 Mar 23 '17 at 10:43

2 Answers2

2

I think you meant How to delete zip file and not a folder.

Here, this should be easy:

File.Delete(zippath);

For deleting inner files and directories :

System.IO.DirectoryInfo di = new DirectoryInfo(path);

foreach (FileInfo file in di.GetFiles())
{
    file.Delete(); 
}
foreach (DirectoryInfo dir in di.GetDirectories())
{
    dir.Delete(true); 
}
Sadique
  • 22,572
  • 7
  • 65
  • 91
  • `File.Exists` is not necessary, in fact it can cause a race condition error. – user247702 Mar 23 '17 at 10:37
  • Thank you. Yes i want to Delete all the files inside zip folder and finally ZIP file also – Neenu Surendran K Mar 23 '17 at 10:39
  • So? The file could (theoretically) be created by another process. Just because the example in the question allows checking if the file exists, it's still unnecessary. So why add additional unneccesary code? Why teach someone a bad practice? – user247702 Mar 23 '17 at 10:40
  • @Stijn Theoretically the above comment could have been typed by a Bot. – Sadique Mar 23 '17 at 10:40
  • @NeenuSurendranK - i realized that `File.Exists` is not required, there is no exception if the file does not exists at all. – Sadique Mar 23 '17 at 10:42
1

Refer below code
I am keeping a copy of txt file and after that creating a new one
If you wish to delete file without vreating backup than jst use File.Delete(path of file)

if (File.Exists(file_path))
            {
                new_file_path = file_path.Replace(".txt", " created on " + File.GetLastWriteTime(file_path).ToString("dd-MM-yyyy hh-mm-ss tt") + ".txt");
                File.Move(file_path, new_file_path);
                File.Delete(file_path);
            }
Saurabh
  • 1,505
  • 6
  • 20
  • 37