use*_*951 3 .net c# file-io compact-framework2.0
我有一个FTP服务器,存储客户端在某个文件夹中发送/上传的文件.客户端将上传3个具有相同名称但扩展名不同的文件.例如,客户端将发送file1.ext1,file1.ext2和file1.ext3.我正在寻找一段代码,它将帮助我找到具有相同名称的文件("file1")然后压缩它们.任何帮助表示赞赏.我编写了这段代码,它获取了文件夹中所有文件的名称:
string path = "somepath";
String[] FileNames = Directory.GetFiles(path);
Run Code Online (Sandbox Code Playgroud)
在调用中使用星号通配符作为文件扩展名GetFiles
,例如:
List<string> files = Directory.GetFiles(pathName, "SpecificFileName.*");
Run Code Online (Sandbox Code Playgroud)
要么:
string[] files = Directory.GetFiles(pathName, "SpecificFileName.*");
Run Code Online (Sandbox Code Playgroud)
这很简单:
string path = "somepath";
String[] FileNames = Directory.GetFiles(path);
Run Code Online (Sandbox Code Playgroud)
您可以使用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
}
Run Code Online (Sandbox Code Playgroud)
如果你没有LINQ,那么任务就不会太困难了.首先,您要对文件进行排序:
Array.Sort(FileNames);
Run Code Online (Sandbox Code Playgroud)
现在,您有一个文件列表,按文件名排序.所以你会有,例如:
file1.ext1
file1.ext2
file1.ext3
file2.ext1
file2.ext2
etc...
Run Code Online (Sandbox Code Playgroud)
然后只需浏览列表,将具有相同基本名称的文件添加到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();
}
Run Code Online (Sandbox Code Playgroud)
我不知道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);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6544 次 |
最近记录: |