Question

I need help in writing a function which zips all files with same name but different extensions in a folder.I am using Ionic.Zip dll to achieve this.I am using .Net compact framework 2.0,VS2005. My code looks like this:

   public void zipFiles()
   {
                string path = "somepath";
                string[] fileNames = Directory.GetFiles(path);
                Array.Sort(fileNames);//sort the filename in ascending order
                string lastFileName = string.Empty;
                string zipFileName = null;
                using (ZipFile zip = new ZipFile())
                    {
                        zip.AlternateEncodingUsage = ZipOption.AsNecessary;
                        zip.AddDirectoryByName("Files");

                        for (int i = 0; i < fileNames.Length; i++)
                        {
                            string baseFileName = fileNames[i];
                            if (baseFileName != lastFileName)
                            {
                                zipFileName=String.Format("Zip_{0}.zip",DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
                                zip.AddFile(baseFileName, "Files");
                                lastFileName = baseFileName;
                            }
                        }
                        zip.Save(zipFileName);
                    }
    }

The problem:The folder will have 3 files with same name but their extensions will be different.Now,these files are being FTPed by a device so the filenames are auto-generated by it and I have no control over it.So,for example,there are 6 files in the folder:"ABC123.DON","ABC123.TGZ","ABC123.TSY","XYZ456.DON","XYZ456.TGZ","XYZ456.TSY". I have to zip the 3 files whose names are "ABC123" together and other 3 files with names "XYZ456".As I said,I wouldnt know the names of the files and my function has to run in background.My current code zips all the files in a single zip folder. Can anyone please help me with this?

Was it helpful?

Solution

Try out the following code

 string path = @"d:\test";

 //First find all the unique file name i.e. ABC123 & XYZ456 as per your example                
 List<string> uniqueFiles=new List<string>();
 foreach (string file in Directory.GetFiles(path))
 {
     if (!uniqueFiles.Contains(Path.GetFileNameWithoutExtension(file)))
         uniqueFiles.Add(Path.GetFileNameWithoutExtension(file));
 }

 foreach (string file in uniqueFiles)
 {
      string[] filesToBeZipped = Directory.GetFiles(@"d:\test",string.Format("{0}.*",file));

      //Zip all the files in filesToBeZipped 
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top