문제

In Windows Explorer, if you copy a file and the file name already exists and you choose not to override the file, Windows Explorer uses a specific file rename algorithm, i.e. it tries to append something like "copy", if this file exists, it appends a number in brackets, which is then incremented, in case these file names also are already taken. Please note, that this is a simplified version of the algorithm. In reality it is more complex.

Since I do not want to reverse engineer this behavior, is there a c# .Net-Api available that gives me direct access to this behavior when copying or creating files?

도움이 되었습니까?

해결책

No.

Point mostly being that this is absolutely not a windows standard behavior, but only done in the Explorer (i.e. it is this particular program that does that).

다른 팁

As @TomTom said, no there isn't, but the Windows Explorer behaviour is easy to reproduce:

Given

var source = @"C:\Temp\Source.txt";
var targetFolder = @"C:\Temp\";

Then,

var targetName = Path.GetFileName(source);
var target = Path.Combine(targetFolder, targetName);
while (File.Exists(target)) {
    targetName = "Copy of "+ targetName;
    var target = Path.Combine(targetFolder, targetName);
}

File.Copy(source, target);

Or you can do a Mac like:

var targetName = Path.GetFileName(source);
for (int i = 0; i < MAX_TRIES; i++) {
    var idx = (i==0)?"":(" ("+i.ToString()+")");
    var target = Path.Combine(targetFolder, targetName+idx);
    if (!File.Exists(target)) break;
}
File.Copy(source, target);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top