这非常简单:
string path = "somepath";
String[] FileNames = Directory.GetFiles(path);
您可以使用 LINQ 按文件名(不带扩展名)对文件进行分组:
var fileGroups = from f in FileNames
group f by Path.GetFileNameWithoutExtension(f) into g
select new { Name = g.Key, FileNames = g };
// each group will have files with the
// same name and different extensions
foreach (var g in fileGroups)
{
// initialize zip file
foreach (var fname in g.FileNames)
{
// add fname to zip
}
// close zip file
}
Update
如果没有 LINQ,该任务也不会困难太多。首先,您要对文件进行排序:
Array.Sort(FileNames);
现在,您有一个文件列表,按文件名排序。因此,您将拥有,例如:
file1.ext1
file1.ext2
file1.ext3
file2.ext1
file2.ext2
etc...
然后只需浏览列表,将具有相同基本名称的文件添加到 zip 文件中,如下所示。请注意,我不知道你是如何创建 zip 文件的,所以我只是做了一个简单的ZipFile
班级。当然,您需要将其替换为您正在使用的任何内容。
string lastFileName = string.Empty;
string zipFileName = null;
ZipFile zipFile = null;
for (int i = 0; i < FileNames.Length; ++i)
{
string baseFileName = Path.GetFileNameWithoutExtension(FileNames[i]);
if (baseFileName != lastFileName)
{
// end of zip file
if (zipFile != null)
{
// close zip file
ZipFile.Close();
}
// create new zip file
zipFileName = baseFileName + ".zip";
zipFile = new ZipFile(zipFileName);
lastFileName = baseFileName;
}
// add this file to the zip
zipFile.Add(FileNames[i]);
}
// be sure to close the last zip file
if (zipFile != null)
{
zipFile.Close();
}
我不知道Compact Framework是否有Path.GetFileNameWithoutExtension
方法。如果没有,那么您可以通过以下方式获取不带扩展名的名称:
string filename = @"c:\dir\subdir\file.ext";
int dotPos = filename.LastIndexOf('.');
int slashPos = filename.LastIndexOf('\\');
string ext;
string name;
int start = (slashPos == -1) ? 0 : slashPos+1;
int length;
if (dotPos == -1 || dotPos < slashPos)
length = filename.Length - start;
else
length = dotPos - start;
string nameWithoutExtension = filename.Substring(start, length);