Fel*_*tto 1 c# wpf copy .net-3.5 windows-7
有时,在我的应用程序中,我想创建一个已存在的文件的副本,但我不想测试该文件是否已存在,我只想创建该文件的副本,如Windows 7 .
例如:文件tips.txt.当我的应用程序复制它时,将创建另一个名为tips - copy.txt的文件.之后,如有必要,提供"副本副本" 提示 - copy - copy.txt.
在这种情况下我能做些什么吗?
Obs:在这个应用程序中,我使用的是.NET 3.5和WPF.
Obs2:我提出这个问题是因为我认为在.NET中已存在类似的东西.
您应该提取文件名和扩展名,然后使用新的格式化名称执行简单的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);
Run Code Online (Sandbox Code Playgroud)
如果你有一个要从中复制的完整路径,事情会变得复杂一些
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));
Run Code Online (Sandbox Code Playgroud)
但如果您真的想模仿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);
Run Code Online (Sandbox Code Playgroud)
如果Windows资源管理器复制以" - 复制"结尾的文件,则会向目标文件添加渐进编号,而不是另一个" - 复制".
您还应该考虑字符串'Copy'是本地化的,因此它在非英语版本的操作系统中会发生变化.