![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
模仿微软的一个拷贝文件功能/// <summary>
/// 文件拷贝
/// </summary>
/// <param name="file1">源文件</param>
/// <param name="file2">目标文件</param>
/// <param name="type">1,跳过,2,替换,3,重命名为例如***(1).txt</param>
public static void copyTo(string file1,ref string file2, int type)
{
//获得文件路径
string path = System.IO.Path.GetDirectoryName(file2);
//获得文件后缀名
string ext = System.IO.Path.GetExtension(file2);
//获得"."之前的所有字符串
string tmpName = file2.Substring(0, file2.LastIndexOf('.'));
//判断目录是否存在,如果不存在则创建
if (!System.IO.Directory.Exists(path))
System.IO.Directory.CreateDirectory(path);
//判断文件是否存在,如果不存在则创建
if (!System.IO.File.Exists(file2))
System.IO.File.Copy(file1, file2);
else//否则
{
switch (type)
{
case 1:
//跳过
break;
case 2:
//删除后创建
System.IO.File.Delete(file2);
System.IO.File.Copy(file1, file2);
break;
case 3:
//断言一万次,遇到break则跳出
for (int i = 1; i <= 9999; i++)
{
//组合字符串,建议打断点看
string tmpFile2 = tmpName +"("+ i +")"+ ext;
//判断组合字符串,是否存在,不存在则创建
if (!System.IO.File.Exists(tmpFile2))
{
System.IO.File.Copy(file1, tmpFile2);
file2 = tmpFile2;
//跳出
break;
}
}
break;
default:
break;
}
}
}