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

posted on 2007-03-05 09:50  章立民研究室  阅读(3572)  评论(0编辑  收藏  举报

导航