gpt4 book ai didi

c# - 像 Windows7 通常那样创建一个文件的副本

转载 作者:太空宇宙 更新时间:2023-11-03 17:15:15 25 4
gpt4 key购买 nike

有时,在我的应用程序中,我想创建一个已经存在的文件的副本,但我不想测试该文件是否已经存在,我只想创建该文件的副本,比如Windows 7 可以。

例如:文件tips.txt。当我的应用复制它时,将创建另一个名为 tips - copy.txt 的文件。之后,如果有必要,一个“copy of a copy”tips - copy - copy.txt

在这种情况下我能做些什么吗?

观察:在此应用程序中,我使用的是 .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);

如果你有完整的复制路径,事情会变得有点复杂

   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 Explorer 复制以“-Copy”结尾的文件,它会向目标文件添加一个递增编号,而不是另一个“-Copy”。
您还应该考虑到字符串“Copy”已本地化,因此它会在非英语版本的操作系统中发生变化。

关于c# - 像 Windows7 通常那样创建一个文件的副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12708372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com