2009-12-30 21 views
37

Necesito copiar un archivo a otra ruta, dejando el original donde está.¿Cómo copiar un archivo a otra ruta?

También quiero poder cambiar el nombre del archivo.

¿Funcionará el método CopyTo de FileInfo?

+0

¿Quiere cambiar el nombre del archivo que acaba de copiar original o? –

+0

cambie el nombre del archivo recién copiado – mrblah

Respuesta

54

Tenga una mirada en File.Copy()

Usando File.Copy puede especificar el nombre de archivo como parte de la cadena de destino.

así que algo como

File.Copy(@"c:\test.txt", @"c:\test\foo.txt"); 

Ver también How to: Copy, Delete, and Move Files and Folders (C# Programming Guide)

+0

Y una cosa importante a tener en cuenta es que puede especificar si el archivo de destino debe sobrescribirse o no agregando el tercer argumento como verdadero o falso. – Arman

+0

No es compatible con 2 servidores diferentes –

4

También es posible usar File.Copy copiar y File.Move para cambiar su nombre epílogos.

// Copy the file (specify true or false to overwrite or not overwrite the destination file if it exists. 
File.Copy(mySourceFileAndPath, myDestinationFileAndPath, [true | false]); 

// EDIT: as "astander" notes correctly, this step is not necessary, as File.Copy can rename already... 
//  However, this code could be adapted to rename the original file after copying 
// Rename the file if the destination file doesn't exist. Throw exception otherwise 
//if (!File.Exists(myRenamedDestinationFileAndPath)) 
// File.Move(myDestinationFileAndPath, myRenamedDestinationFileAndPath); 
//else 
// throw new IOException("Failed to rename file after copying, because destination file exists!"); 

EDITAR
como comentario el código "renombrar", porque File.Copy ya se puede copiar y cambiar el nombre en un solo paso, como Astander observó correctamente en los comentarios.

Sin embargo, el código de cambio de nombre podría adaptarse si el OP desea cambiar el nombre del archivo de origen después de haber sido copiado a una nueva ubicación.

+0

No tiene que copiar y renombrar, puede hacerlo en un solo paso usando File.Copy –

+0

Tiene sentido ... Últimamente he usado mucho el cambio de nombre de código usando File.Move que ni siquiera pensé en File.Copy pudiendo cambiar el nombre también :-) –

2

File :: Copy copiará el archivo en la carpeta de destino y File :: Move puede mover y cambiar el nombre de un archivo.

6

Sí. Se trabajará: FileInfo.CopyTo Method

Utilice este método para permitir o impedir la sobrescritura de un archivo existente. Utilice el método CopyTo para evitar la sobrescritura de un archivo existente de forma predeterminada.

Todas las otras respuestas son correctas, pero ya que preguntas para FileInfo, he aquí una muestra:

FileInfo fi = new FileInfo(@"c:\yourfile.ext"); 
fi.CopyTo(@"d:\anotherfile.ext", true); // existing file will be overwritten 
7

He intentado copiar un archivo XML desde un lugar a otro. Aquí está mi código:

public void SaveStockInfoToAnotherFile() 
{ 
    string sourcePath = @"C:\inetpub\wwwroot"; 
    string destinationPath = @"G:\ProjectBO\ForFutureAnalysis"; 
    string sourceFileName = "startingStock.xml"; 
    string destinationFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xml"; // Don't mind this. I did this because I needed to name the copied files with respect to time. 
    string sourceFile = System.IO.Path.Combine(sourcePath, sourceFileName); 
    string destinationFile = System.IO.Path.Combine(destinationPath, destinationFileName); 

    if (!System.IO.Directory.Exists(destinationPath)) 
     { 
     System.IO.Directory.CreateDirectory(destinationPath); 
     } 
    System.IO.File.Copy(sourceFile, destinationFile, true); 
} 

Entonces me llamaron a esta función dentro de una función timer_elapsed de cierto intervalo que creo que no es necesario para ver. Funcionó. Espero que esto ayude.

-1

para copiar la carpeta uso dos cuadros de texto para conocer el lugar de la carpeta Y Antera cuadro de texto Para saber lo que la carpeta de copiarlo y este es el código

MessageBox.Show("The File is Create in The Place Of The Programe If you Don't Write The Place Of copy And You write Only Name Of Folder");// It Is To Help The User TO Know 
      if (Fromtb.Text=="") 
     { 
      MessageBox.Show("Ples You Should Write All Text Box"); 
      Fromtb.Select(); 
      return; 
     } 
     else if (Nametb.Text == "") 
     { 
      MessageBox.Show("Ples You Should Write The Third Text Box"); 
      Nametb.Select(); 
      return; 
     } 
     else if (Totb.Text == "") 
     { 
      MessageBox.Show("Ples You Should Write The Second Text Box"); 
      Totb.Select(); 
      return; 
     } 

     string fileName = Nametb.Text; 
     string sourcePath = @"" + Fromtb.Text; 
     string targetPath = @"" + Totb.Text; 


     string sourceFile = System.IO.Path.Combine(sourcePath, fileName); 
     string destFile = System.IO.Path.Combine(targetPath, fileName); 


     if (!System.IO.Directory.Exists(targetPath)) 
     { 
      System.IO.Directory.CreateDirectory(targetPath); 
      //when The User Write The New Folder It Will Create 
      MessageBox.Show("The File is Create in "+" "+Totb.Text); 
     } 


     System.IO.File.Copy(sourceFile, destFile, true); 


     if (System.IO.Directory.Exists(sourcePath)) 
     { 
      string[] files = System.IO.Directory.GetFiles(sourcePath); 


      foreach (string s in files) 
      { 
       fileName = System.IO.Path.GetFileName(s); 
       destFile = System.IO.Path.Combine(targetPath, fileName); 
       System.IO.File.Copy(s, destFile, true); 

      } 
      MessageBox.Show("The File is copy To " + Totb.Text); 

     } 
0

Esto es lo que hice para mover un archivo de prueba desde las descargas al escritorio. Espero que sea útil.

private void button1_Click(object sender, EventArgs e)//Copy files to the desktop 
    { 
     string sourcePath = @"C:\Users\UsreName\Downloads"; 
     string targetPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); 
     string[] shortcuts = { 
      "FileCopyTest.txt"}; 

     try 
     { 
      listbox1.Items.Add("Starting: Copy shortcuts to dektop."); 
      for (int i = 0; i < shortcuts.Length; i++) 
      { 
       if (shortcuts[i]!= null) 
       { 
        File.Copy(Path.Combine(sourcePath, shortcuts[i]), Path.Combine(targetPath, shortcuts[i]), true);       
        listbox1.Items.Add(shortcuts[i] + " was moved to desktop!"); 
       } 
       else 
       { 
        listbox1.Items.Add("Shortcut " + shortcuts[i] + " Not found!"); 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
      listbox1.Items.Add("Unable to Copy file. Error : " + ex); 
     } 
    }   
0
string directoryPath = Path.GetDirectoryName(destinationFileName); 

// If directory doesn't exist create one 
if (!Directory.Exists(directoryPath)) 
{ 
DirectoryInfo di = Directory.CreateDirectory(directoryPath); 
} 

File.Copy(sourceFileName, destinationFileName); 
Cuestiones relacionadas