简体   繁体   English

C#更改DOS通配符上的文件名

[英]C# change file name on DOS wildcards

We have a .net program which essentially copies the files from one folder to another and , often, changes the files' names during the copying. 我们有一个.net程序,该程序实际上将文件从一个文件夹复制到另一个文件夹,并且通常在复制过程中更改文件的名称。 The customer provide the file names to be copied & the target file names using DOS style wildcards. 客户使用DOS样式通配符提供要复制的文件名和目标文件名。

For example: 例如:

Source: *.log Target: *.txt 来源:*。log目标:*。txt

Copy aa.log to aa.txt , bb2.1.log to bb2.1.txt etc 将aa.log复制到aa.txt,将bb2.1.log复制到bb2.1.txt等

or 要么

Source: abc*.csv Target: KK*_123.csv 来源:abc * .csv目标:KK * _123.csv

Copy abcxyz.csv to KKabcxyz_123.csv, abc1722.mm.csv to KKabc1722.mm_123.csv 将abcxyz.csv复制到KKabcxyz_123.csv,abc1722.mm.csv复制到KKabc1722.mm_123.csv

How can I implement such copying / renaming in C# or VB.net ? 如何在C#或VB.net中实现这种复制/重命名?

File.Copy(SourceFile, TargetFile ) doesn't support wildcards (*,?) in the file names, so probably the question is, how to generate the target file name ? File.Copy(SourceFile, TargetFile )在文件名中不支持通配符(* ,?),因此可能的问题是,如何生成目标文件名?

PS If it's absolutely necessary I can enforce some limitations on the source / target file names, but I'd like to avoid it. PS:如果绝对必要,我可以对源/目标文件名实施一些限制,但我想避免这样做。

PPS If necessary, the process can be divided to the separate parts. PPS如有必要,可以将过程分为单独的部分。 Example #2 : Source: abc*.csv Target: KK*_123.csv Example#2:来源:abc * .csv目标:KK * _123.csv

could be replaced with 可以替换为
Source: abc*.csv Target: KK*.csv 来源:abc * .csv目标:KK * .csv

and Source: KK*.csv Target: *_123.csv 和来源:KK * .csv目标:* _ 123.csv

.

I'm not aware of a completely built-in solution, but .NET will do pattern matching for you. 我不知道一个完全内置的解决方案,但是.NET将为您进行模式匹配。 Directory.EnumerateFiles(string, string) accepts a pattern to match source files on. Directory.EnumerateFiles(string,string)接受一种模式来匹配源文件。 You could do something like 你可以做类似的事情

foreach (var sourceFile in Directory.EnumerateFiles(myPath, thePattern))
{
    var targetFile = ApplyPattern(sourceFile, thePattern);
    File.Copy(sourceFile, targetFile);
}

You would need to implement ApplyPattern yourself by examining the sourceFile found by EnumerateFiles and applying the placeholder logic. 您需要通过检查EnumerateFiles找到的sourceFile并应用占位符逻辑来自己实现ApplyPattern。

Perhaps there is a better solution that I'm not aware of. 也许有一个我不知道的更好的解决方案。 If not, this at least will handle the source matching for you. 如果不是,则至少将为您处理匹配的源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM