天天看點

Visual C# - 讀者詢問如何複制目錄以及目錄下所有的子目錄與檔案

原發問問題:

老師:你好,新年快樂.

IO與資料存取密訣裡有提到檔案複制及移動目錄.

但如何複制整個目錄及目錄下面的所有子目錄及所有檔案到某個地方?

還有如何使用以前*.*的通配符來複制所有檔案?

謝謝.請幫忙解答

解答:

親愛的讀者您好

很感謝您對于章立民研究室的支援

有關于您提到的問題

回複如下

如果需要複制整個目錄的内容到另一個目錄,以Visual C#來說,最簡便的方法,就是使用Microsoft.VisualBasic.Devices命名空間的My.Computer.FileSystem對象之CopyDirectory方法,它擁有下列四個多載版本(注:相關參數的用途請參閱My.Computer.FileSystem. CopyDirectory方法的說明)

public void CopyDirectory

(

 string sourceDirectoryName,

 string destinationDirectoryName

)

-或-

 string destinationDirectoryName,

 bool overwrite

 UIOption showUI

 UIOption showUI,

 UICancelOption onUserCancel

請注意:

要使用Visual Basic的My對象之前,必須先加入對Microsoft.VisualBasic的參考,再彙入适當的命名空間,例如:

using Microsoft.VisualBasic.Devices;

就可以在C#中使用與My相似的文法來撰寫程式。

                             圖表1

如圖表1所示,程式範例示範如何複制目錄,茲将程式代碼列示如下:

public partial class DemoForm001 : Form

{

 ...

 private void DemoForm001_Load(object sender, EventArgs e)

 {

  this.showUIComboBox.DataSource =

    System.Enum.GetNames(typeof(UIOption));

  this.showUIComboBox.SelectedIndex = 1;

  this.onUserCancelComboBox.DataSource =

    System.Enum.GetNames(typeof(UICancelOption));

  this.onUserCancelComboBox.SelectedIndex = 0;

 }

 private void FileBrowseButton_Click(object sender, EventArgs e)

  FolderBrowserDialog folderDialog = new FolderBrowserDialog();

  folderDialog.RootFolder = Environment.SpecialFolder.MyComputer;

  if ((folderDialog.ShowDialog() ==

    System.Windows.Forms.DialogResult.OK))

  {

   this.FileToBeCopiedTextBox.Text = folderDialog.SelectedPath;

  }

 private void DirectoryBrowseButton_Click(object sender, EventArgs e)

   this.DestionFileTextBox.Text = folderDialog.SelectedPath;

 private void btnCopyFolder_Click(object sender, EventArgs e)

  Computer MyComputer = new Computer();

  if(this.DestionFileTextBox.Text == "")

   MessageBox.Show("您并未指定複制目标資料夾。", "請注意");

   this.DestionFileTextBox.Focus();

   this.DestionFileTextBox.SelectionStart =

     this.DestionFileTextBox.Text.Length;

   return;

  try

   MyComputer.FileSystem.CopyDirectory(

     this.FileToBeCopiedTextBox.Text,

     this.DestionFileTextBox.Text,

     (UIOption)(System.Enum.Parse(typeof(UIOption),

     showUIComboBox.SelectedItem.ToString())),

     (UICancelOption)(System.Enum.Parse(typeof(UICancelOption),

     onUserCancelComboBox.SelectedItem.ToString())));

   // 啟動 Windows 檔案總管。

   Process.Start("explorer.exe",

     Path.GetDirectoryName(this.DestionFileTextBox.Text));

  catch (Exception ex)

   MessageBox.Show(ex.Message);