C#查找文件、复制文件

时间:2024-05-22 09:13:44

在C盘所在路径1 搜指扩展名的所有文件,得到在所在文件的路径,

然后用去掉扩展名的文件名,去搜D盘相同的路径下是否有这个文件,

再将这个文件复制到C盘所在文件的路径下

C#查找文件、复制文件

 

  private void btnFindTxt_Click(object sender, EventArgs e)
        {
            //水平进度
            //最大 最小值
    
            progressBarControl1.Properties.Minimum = 0;

            progressBarControl1.Position = 0;//当前值
            progressBarControl1.Properties.ShowTitle = true;//是否显示进度数据
            //是否显示百分比
            progressBarControl1.Properties.PercentView = true;

             //Stopwatch提供一组方法和属性,可用于准确地测量运行时间
             Stopwatch sw = new Stopwatch();
             sw.Start();

             string filepath = this.txtPath.Text.Trim();
             string filepathD = this.txtPathD.Text.Trim();
             string filename = this.txtFile.Text.Trim();   //如果模糊查找则文件名用*,如 *.xls、*bbb.rar
             int n = Convert.ToInt32(txtInt.Text.Trim());

             //string[] files = Directory.GetFiles(filepath + @"\", "*.xls");
             //string[] files = Directory.GetFiles(filepath + @"\", filename);  //查找时不包括子目录
             try
             {
                 string[] files = Directory.GetFiles(filepath + @"\", filename, SearchOption.AllDirectories);   //查找时包括子目录
                 foreach (string file in files)
                 {
                     //string fileD = file.Substring(0, n);  //取文件名的前n个字符
                     string filenameD = Path.GetFileNameWithoutExtension(file);
                     string[] fileDs = Directory.GetFiles(filepathD + @"\", filenameD, SearchOption.AllDirectories);   //包括子目录

                     foreach (string fileD in fileDs)
                     {
                         string pathD = Path.GetDirectoryName(fileD) + @"\";
                         string pathC = "C" + pathD.Remove(0, 1);
                         saveFile(pathC, fileD);
                     }
                 }

                 sw.Stop();
                 TimeSpan dt = sw.Elapsed;
                 progressBarControl1.Properties.Maximum = Convert.ToInt32(dt.TotalMilliseconds);    //把用时 变成毫秒再转化为整数int


                 for (int i = 0; i < progressBarControl1.Properties.Maximum; i++)
                 {
                     //处理当前消息队列中的所有windows消息
                     Application.DoEvents();
                     //当前线程挂起指定的时间,这个是为了演示
                     //System.Threading.Thread.Sleep(12);
                     //执行步长
                     progressBarControl1.PerformStep();
                 }
                 MessageBox.Show("查找并复制成功");

             }
             catch
             {
                 MessageBox.Show("数据异常或者有受权限限制受读写保护的子文件夹!");
             }            
        }


        public void saveFile(string path, string fileName)
        {
            FileInfo file = new FileInfo(fileName);
            string newName = file.Name;
            file.CopyTo(path + @"\" + newName, true);
        }