你應該提取文件名,然後擴展做一個簡單的File.Copy用新格式的名稱
string fileName = "tips.txt";
string file = Path.GetFileNameWithoutExtension(fileName);
string ext = Path.GetExtension(fileName);
File.Copy(fileName, string.Format("{0} - Copy{1}", file, ext);
事情得到了一點更復雜的,如果你有一個FULLPATH從
string fileName = "C:\\test\\tips.txt";
string path = Path.GetDirectoryName(fileName);
string file = Path.GetFileNameWithoutExtension(fileName);
string ext = Path.GetExtension(fileName);
File.Copy(fileName, Path.Combine(path, string.Format("{0} - Copy{1}", file, ext));
複製,但如果你真的想模仿Windows資源管理器的行爲,我們應該做的:
string fileName = "C:\\test\\tips.txt";
string path = Path.GetDirectoryName(fileName);
string file = Path.GetFileNameWithoutExtension(fileName);
string ext = Path.GetExtension(fileName);
if(file.EndsWith(" - Copy")) file = file.Remove(0, file.Length - 7);
string destFile = Path.Combine(path, string.Format("{0} - Copy{1}", file, ext));
int num = 2;
while(File.Exists(destFile))
{
destFile = Path.Combine(path, string.Format("{0} - Copy ({1}){2}", file, num, ext));
num++;
}
File.Copy(fileName, destFile);
如果Windows資源管理器的副本與「結尾的文件 - 複製「,它將累進數字添加到目標文件,而不是另一個」 - 複製「。
您還應該考慮字符串「複製」是本地化的,因此它在操作系統的非英文版本中發生變化。
爲什麼你不想測試這個文件是否已經存在,Windows在給你提示的時候確實存在,那你爲什麼不去做Windows? –
嘗試在文件上使用ctrl-c ctrl-v。我想創建相同的功能(因爲我認爲.NET中已經存在類似的東西) –