[英]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.