服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

复制文件夹内容和删除整个文件夹的2个函数


  // ======================================================
  
  // 实现一个静态方法将指定文件夹下面的所有内容copy到目标文件夹下面
  
  // 如果目标文件夹为只读属性就会报错。
  
  // april 18april2005 in stu
  
  // ======================================================
  
  public static void copydir(string srcpath,string aimpath)
  
  {
  
  try
  
  {
  
  // 检查目标目录是否以目录分割字符结束如果不是则添加之
  
  if(aimpath[aimpath.length-1] != path.directoryseparatorchar)
  
  aimpath += path.directoryseparatorchar;
  
  // 判断目标目录是否存在如果不存在则新建之
  
  if(!directory.exists(aimpath)) directory.createdirectory(aimpath);
  
  // 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
  
  // 如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
  
  // string[] filelist = directory.getfiles(srcpath);
  
  string[] filelist = directory.getfilesystementries(srcpath);
  
  // 遍历所有的文件和目录
  
  foreach(string file in filelist)
  
  {
  
  // 先当作目录处理如果存在这个目录就递归copy该目录下面的文件
  
  if(directory.exists(file))
  
  copydir(file,aimpath+path.getfilename(file));
  
  // 否则直接copy文件
  
  else
  
  file.copy(file,aimpath+path.getfilename(file),true);
  
  }
  
  }
  
  catch (exception e)
  
  {
  
  messagebox.show (e.tostring());
  
  }
  
  }
  
  
  // ======================================================
  // 实现一个静态方法将指定文件夹下面的所有内容detele
  // 测试的时候要小心操作,删除之后无法恢复。
  // april 18april2005 in stu
  // ======================================================
  public static void deletedir(string aimpath)
  {
  try
  {
  // 检查目标目录是否以目录分割字符结束如果不是则添加之
  if(aimpath[aimpath.length-1] != path.directoryseparatorchar)
  aimpath += path.directoryseparatorchar;
  // 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
  // 如果你指向delete目标文件下面的文件而不包含目录请使用下面的方法
  // string[] filelist = directory.getfiles(aimpath);
  string[] filelist = directory.getfilesystementries(aimpath);
  // 遍历所有的文件和目录
  foreach(string file in filelist)
  {
  // 先当作目录处理如果存在这个目录就递归delete该目录下面的文件
  if(directory.exists(file))
  {
  deletedir(aimpath+path.getfilename(file));
  }
  // 否则直接delete文件
  else
  {
  file.delete (aimpath+path.getfilename(file));
  }
  }
  //删除文件夹
  system.io .directory .delete (aimpath,true);
  }
  catch (exception e)
  {
  messagebox.show (e.tostring());
  }
  }

扫描关注微信公众号