一聚教程网:一个值得你收藏的教程网站

热门教程

asp.net实现文件和文件夹的复制的教程

时间:2022-06-25 03:01:17 编辑:袖梨 来源:一聚教程网

话不多说,请看代码:

privatevoidbtnSave_Click(objectsender, EventArgs e)//文件复制、保存方法
    {
      #region 静态复制文件(写死)
      stringdesPath =@"c:11.chm";
      if(File.Exists(desPath))
      {
        //目标文件已存在
        if(MessageBox.Show(("文件已存在,是否覆盖"),"询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
        == DialogResult.Yes) //选择Yes 确定覆盖
        {
          //复制文件
          File.Copy(@"c:lsw3.chm", desPath,true);
          MessageBox.Show("覆盖成功");
        }
      }
      else//文件不存在
      {
        //开始复制
        File.Copy(@"c:lsw3.chm", desPath,true);
        MessageBox.Show("复制成功");
      }
      //显示打开对话框,返回值为dialogResult类型,如果是OK,则用户点击的为打开,否则为取消
      openFileDialog1.InitialDirectory=(@"c:1");//选择文件时的默认位置
      //openfilediaglog1.filter中的fileter是过滤器的作用
      //showdialog()显示对话框的方法.
      openFileDialog1.Filter ="可执行程序|*.exe|TXT文本|*.txt|图片文件|*.jpg|所有文件|*.*";//可保存类型
 
      if(openFileDialog1.ShowDialog() == DialogResult.OK)//点击了打开
      {
        if(saveFileDialog1.ShowDialog() == DialogResult.OK)//说明点yes 也就是确认保存
        {
          File.Copy(openFileDialog1.FileName, saveFileDialog1.FileName,true);
          MessageBox.Show("保存完成");
        }
      }
#endregion
    }
    //File类是对文件操作的,包括复制、保存、创建时间、修改时间等等等等。
    //Directory功能类似file
    #region 动态
    privatevoidbtnCopyContents_Click(objectsender, EventArgs e)
    {
      stringoldDir, newDir;//分别是原文件夹和目标文件夹
      FolderBrowserDialog sourceFolder =newFolderBrowserDialog();//动态生成了folderbrowserdialog这个控件 不需要拖控件
      sourceFolder.Description ="请选择要复制的文件夹";//显示了一个简单说明
      if(sourceFolder.ShowDialog()==DialogResult.OK)//点了确定
      {
        oldDir = sourceFolder.SelectedPath;
        sourceFolder.Description ="请选择要复制到的文件夹";//修改了一下sourcefolder的说明文字 便于使用者使用
        if(sourceFolder.ShowDialog()== DialogResult.OK)//如果确定 那么执行下面代码块代码
        {
          newDir = sourceFolder.SelectedPath;
          //获取当前要复制的文件夹中的所有文件(注意!不包含下级文件夹及其中的文件)
          string[] files = Directory.GetFiles(oldDir);//定义了个字符数组来接收源文件内需要复制的文件
          foreach(stringfilepathinfiles)//也可以用for语句
          {
            //File.Copy(filepath,newDir+"\"+filepath.Substring(filepath.LastIndexOf("\")+1),true);
          //拆分了一下,更为简洁
            stringnFileName ;//定义一个string类型,来获取文件名
            nFileName = filepath.Substring(filepath.LastIndexOf("\") + 1);//获取要复制的文件夹里的文件名
            File.Copy(filepath, newDir +"\"+ nFileName,true); //最后得出要复制的文件夹以及文件夹里的文件名并进行复制
          }
          //MessageBox.Show("复制完成");
        }
        //MessageBox.Show(sourceFolder.SelectedPath);
 
      }
    }
    #endregion

热门栏目