摘要:Visual C# - 讀者詢問如何複製目錄以及目錄下所有的子目錄與檔案
原發問問題:
IO與資料存取密訣裡有提到檔案複製及移動目錄.
但如何複製整個目錄及目錄下面的所有子目錄及所有檔案到某個地方?
還有如何使用以前*.*的萬用字來複製所有檔案?
謝謝.請幫忙解答
解答:
親愛的讀者您好
很感謝您對於章立民研究室的支持
有關於您提到的問題
回覆如下
如果需要複製整個目錄的內容到另一個目錄,以Visual C#來說,最簡便的方法,就是使用Microsoft.VisualBasic.Devices命名空間的My.Computer.FileSystem物件之CopyDirectory方法,它擁有下列四個多載版本(註:相關參數的用途請參閱My.Computer.FileSystem. CopyDirectory方法的說明)
public void CopyDirectory
(
string sourceDirectoryName,
string destinationDirectoryName
)
-或-
public void CopyDirectory
(
string sourceDirectoryName,
string destinationDirectoryName,
bool overwrite
)
-或-
public void CopyDirectory
(
string sourceDirectoryName,
string destinationDirectoryName,
UIOption showUI
)
-或-
public void CopyDirectory
(
string sourceDirectoryName,
string destinationDirectoryName,
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)
{
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
folderDialog.RootFolder = Environment.SpecialFolder.MyComputer;
if ((folderDialog.ShowDialog() ==
System.Windows.Forms.DialogResult.OK))
{
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);
}
}
章立民研究室