Saving Files with the Same Name in Same folder

Jun 25, 2010 at 9:28 PM
Edited Jun 25, 2010 at 9:31 PM

This method takes a String array with file names from a variety of locations. I am wanting to zip those files into one directory. However if two files have the same name, I get an error and the operation does not complete. Is there a way to deal with this with DotNetZip? For example if there are two files named "Sample.txt", could the next one be automatically named "Sample(2).txt"? This way all the specified files will be saved without worries of overwriting. Thanks for your help btw the Parameters object just contains the String[], A date object, and a String destination Path. Let me know if you need any more of my other classes.

 

class ZipNow
    {
        
        String[] files;
        DateTime date;
        String dPath;
        public Parameters param;

        public ZipNow() { }

        
        public bool zip(Object param) //save files in one folder from multiple locations
        {
            Parameters prm = (Parameters)param;

            try
            {
                ZipFile zip = new ZipFile();

                //add all files to the zip file
                for (int i = 0; i < prm.getFiles().Length; i++)
                {
                    if (File.Exists(prm.getFiles()[i]))
                    {
                        zip.AddFile(prm.getFiles()[i],"Archive");
                        
                    }
                    else
                    {
                        MessageBox.Show("File " + prm.getFiles()[i].ToString() + " Does not exist.  File will not be included in zip Package");
                        continue;
                    }
                }
                
                //save the zip file to the specified FilePath
                zip.Save(prm.getDPath() + "\\" + prm.getDate().Month.ToString() + "_" + prm.getDate().Day.ToString() + "_" + prm.getDate().Year.ToString() + ".zip");
                return true;
                //MessageBox.Show("Operation Complete");
            }
            catch (FileNotFoundException exFile)
            {
                MessageBox.Show("File not found " + exFile.Message);
                return false;
            }
            catch (DirectoryNotFoundException exDirectory)
            {
                MessageBox.Show("Directory not Found " + exDirectory.Message);
                return false;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exeption" + ex.Message);
                return false;
            }
            //return true;


        }


        public String[] getFiles()
        {
            return this.files;
        }
    }