[英]Folder and file copy c#
我再次需要你的帮助:)
public partial class Form1 : Form
{
const string v_datoteko = @"\\Cartman-pc\k\test"; // prenese v katero koli mapo le, da imaš dovoljenje!
const string iz_datoteke = @".\posnetki07"; // mora biti v isti mapi kot .exe!( primer: posnetki s v c:\ program mora biti v c:\ ne v mapi. !
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DirectoryInfo dir = new DirectoryInfo(iz_datoteke);
if (!dir.Exists)
{
throw new Exception("Mapa ne obstaja: " + iz_datoteke);
}
if (!Directory.Exists(v_datoteko))
{
Directory.CreateDirectory(v_datoteko);
}
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(v_datoteko, file.Name);
file.CopyTo(temppath);
}
}
程序工作正常,直到我想复制文件,已经在文件夹中,然后我收到一个错误。 所以我知道我需要做点什么
//if ( File.Exists( path ) )
File.Move( path, path + ".old" );
但我是c#的新手,我不知道放在哪里。 :)所以thx的帮助
你只需要做
file.CopyTo(temppath, false);
是否覆盖的第二个参数。 您可以将其设为false,因为您只需要复制文件(如果不存在)。
如果需要覆盖,则将其设置为true。
FileInfo.CopyTo方法(String,Boolean)
如果存在文件,则需要使用新名称复制文件
temppath = File.Exists(temppath)? temppath+ ".old":temppath;
File.CopyTo(temppath);
将文件路径检查放在file.CopyTo(temppath)之前;
if(File.Exists(temppath))
{
File.Move( temppath, temppath+ ".old" );
// instead of "old" use something unique such as timestamp
}
file.CopyTo(temppath);
foreach (FileInfo file in files)
{
string temppath = Path.Combine(v_datoteko, file.Name);
if(File.Exists(temppath))
file.CopyTo(Path.Combine(v_datoteko, file.Name + ".old");
else
file.CopyTo(temppath);
}
围绕file.CopyTo(temppath);
:
if (!temppath.exists){
file.CopyTo(temppath);
}
你也可以捕获错误,最后生成提示文件的错误列表,没有复制:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.