2009-12-30 96 views
37

我需要將文件複製到另一個路徑,將原始文件保留在原來的位置。如何將文件複製到另一個路徑?

我也希望能夠重命名文件。

FileInfo的CopyTo方法是否工作?

+0

你要重命名的原件或新複製的文件嗎? – 2009-12-30 12:34:36

+0

重命名新複製的文件 – mrblah 2009-12-30 15:42:50

回答

54

看一看File.Copy()

使用File.Copy您可以指定新的文件名作爲目標字符串的一部分。

因此,像

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

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

+0

重要的是要注意的是,您可以通過將第三個參數添加爲true或false來指定目標文件是否必須被覆蓋。 – Arman 2016-10-10 09:51:39

+0

它不支持2服務器不同 – 2017-02-10 02:37:18

4

見你也可以使用File.Copy複製和File.Move它後記重命名。

// 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!"); 

編輯
註釋掉「重命名」代碼,因爲File.Copy已經可以複製並在一個步驟重新命名,如astander在評論正確地指出。

但是,如果OP想要在源文件被複制到新位置後重命名源文件,則可以修改重命名代碼。

+0

你不必複製和重命名,你可以使用File.Copy – 2009-12-30 12:33:15

+0

一步到位做到這一點有道理......我最近使用File.Move做了很多文件重命名我甚至沒有想到File.Copy能夠重命名:-) – 2009-12-30 12:35:07

2

File :: Copy將文件複製到目標文件夾,File :: Move可以同時移動和重命名文件。

6

是的。它會工作:FileInfo.CopyTo Method

使用此方法來允許或防止覆蓋現有的文件。使用CopyTo方法可防止默認覆蓋現有文件。

所有其他的反應是正確的,但既然你問了FileInfo,這裏有一個例子:

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

我試圖從一個位置複製一個XML文件到另一個。這裏是我的代碼:

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

然後我打電話一定的時間間隔,我認爲你不需要看到的timer_elapsed函數內部此功能。有效。希望這可以幫助。

-1

來複制我用兩個文本框要知道文件夾和地點花葯文本框知道什麼文件夾複製它的文件夾,這是代碼

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

這是我做的移動從下載到桌面的測試文件。 我希望它有用。

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); 
相關問題