0

我需要帮助编写一个函数来压缩文件夹中所有具有相同名称但扩展名不同的文件。我正在使用Ionic.Zip dll来实现这一点。我正在使用.Net compact framework 2.0,VS2005。我的代码如下所示:

   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);
                    }
    }

问题:该文件夹将有 3 个同名的文件,但它们的扩展名会不同。现在,这些文件正在由设备通过 FTP 传输,因此文件名是由它自动生成的,我无法控制它。所以,例如,文件夹中有6个文件:"ABC123.DON","ABC123.TGZ","ABC123.TSY","XYZ456.DON","XYZ456.TGZ","XYZ456.TSY"。我必须将 3 个名称为“ABC123”的文件和其他 3 个名称为“XYZ456”的文件压缩在一起。正如我所说,我不知道文件的名称,我的函数必须在后台运行。我当前的代码压缩所有单个 zip 文件夹中的文件。谁能帮我解决这个问题?

4

1 回答 1

1

试试下面的代码

 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 
 }
于 2013-04-19T05:41:41.397 回答