Visual C# 2005 – 如何使用通配符 *.* 複製所有文件

原發問問題:

老師:你好,新年快樂.
IO與數據存取密訣裏有提到文件複製及移動目錄.
但如何使用以前*.*的通配符來複制所有文件? 謝謝.請幫忙解答

解答:

親愛的讀者您好

很感謝您對於章立民研究室的支持
有關於您提到的問題
回覆如下
                           圖表1
如圖表1所示,程序範例示範如何利用通配符 *,來複制數據夾內符合條件的所有文件,請特別注意我們是如何比對數據夾內的文件名稱,並執行文件複製的動作。茲將程序代碼列示如下:

private void btnCopyFolder_Click(object sender, EventArgs e)
{
 string[] temp;
 string tempStr;
 string[] fileNames;
 string sourceDir;
 string destinationDir;
 string mappingStr;
 
 try
 {
  sourceDir = textBox1.Text.Substring(0, textBox1.Text.LastIndexOf(@"\"));
  destinationDir = this.DestionFileTextBox.Text;
 
  // 取得用戶輸入的路徑所代表目錄之文件名稱集合。
  temp = Directory.GetFiles(sourceDir);
 
  for(int i = 0;i < temp.Length;i++)
  {
   tempStr = temp[i].Substring(temp[i].LastIndexOf(@"\") + 1);
   temp[i] = tempStr;
  }
 
  mappingStr =
    textBox1.Text.Substring(textBox1.Text.LastIndexOf(@"\") + 1,
    textBox1.Text.Length - textBox1.Text.LastIndexOf(@"\") - 2);
 
  // 將數組排序。
  Array.Sort(temp, new CaseInsensitiveComparer());
  fileNames = temp;
 
  // 搜尋已排序之數組。
  int fileIndex =
    Array.BinarySearch(
    fileNames, mappingStr, new CaseInsensitiveComparer());
 
  if(fileIndex < 0)
  {
   fileIndex = ~fileIndex;
  }
 
  int matchIndex = 0;
 
  // 計算符合條件的筆數。
  while (fileIndex + matchIndex < fileNames.Length)
  {
   if(!(fileNames[fileIndex + matchIndex].StartsWith(
     mappingStr, StringComparison.CurrentCulture)))
   {
    break;
   }
  
   matchIndex += 1;
  }
 
  string[] returnArray = null;
 
  // 如果有找到符合條件的數據,
  // 則將數據複製到數組變量。
  if (matchIndex > 0)
  {
   returnArray = new string[matchIndex];
  
   Array.Copy(fileNames, fileIndex, returnArray, 0, matchIndex);
  
   for (int i = 0; i < returnArray.Length; i++)
   {
    File.Copy(
      sourceDir + @"\" + returnArray[i],
      destinationDir + @"\" + returnArray[i], true);
   }
  
   // 啓動 Windows 文件總管。
   Process.Start("explorer.exe", this.DestionFileTextBox.Text);
  }
 }
 catch (Exception ex)
 {
  MessageBox.Show(ex.Message);
 }
}

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;
 }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章