简体   繁体   中英

Folder and file copy c#

I need your help once again :)

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);
        }

    }

Program works fine until i want to copy file,that is allready in a folder then i get an error. so i know i need to do something like

//if ( File.Exists( path ) ) 
     File.Move( path, path + ".old" );  

but i am new to c# and i don't know where to put it. :) so thx for your help

you only need to do

file.CopyTo(temppath, false);

second parameter for overwrite or not. you can give it as false since you only need to copy the file if not exist.

if you need to overwrite then set it as true.

FileInfo.CopyTo Method (String, Boolean)


if you need to copy the file with new name if file exist

temppath = File.Exists(temppath)? temppath+ ".old":temppath;

File.CopyTo(temppath);

Put the file path check before 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);
}

Around file.CopyTo(temppath); :

if (!temppath.exists){
  file.CopyTo(temppath);
}

Also you could catch errors and at the end generate error list mentioning files, that were not copied :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM