We have a .net program which essentially copies the files from one folder to another and , often, changes the files' names during the copying. The customer provide the file names to be copied & the target file names using DOS style wildcards.
For example:
Source: *.log Target: *.txt
Copy aa.log to aa.txt , bb2.1.log to bb2.1.txt etc
or
Source: abc*.csv Target: KK*_123.csv
Copy abcxyz.csv to KKabcxyz_123.csv, abc1722.mm.csv to KKabc1722.mm_123.csv
How can I implement such copying / renaming in C# or 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 ?
PS If it's absolutely necessary I can enforce some limitations on the source / target file names, but I'd like to avoid it.
PPS If necessary, the process can be divided to the separate parts. Example #2 : Source: abc*.csv Target: KK*_123.csv
could be replaced with
Source: abc*.csv Target: KK*.csv
and Source: KK*.csv Target: *_123.csv
.
I'm not aware of a completely built-in solution, but .NET will do pattern matching for you. Directory.EnumerateFiles(string, string) accepts a pattern to match source files on. 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.
Perhaps there is a better solution that I'm not aware of. If not, this at least will handle the source matching for you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.