文件移动(Move)操作和文件的复制(Copy)是C#程式开发经常遇到的方法,根据传入的源文件地址和目标文件地址参数,实现对文件的操作。实现代码如下:

  1. Move操作代码:
    public static void MoveFolder(string sourcePath, string destPath)
            {
                if (Directory.Exists(sourcePath))
                {
                    if (!Directory.Exists(destPath))
                    {
                        //目标目录不存在则创建  
                        try
                        {
                            Directory.CreateDirectory(destPath);
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("创建目标目录失败:" + ex.Message);
                        }
                    }
                    //获得源文件下所有文件  
                    List<string> files = new List<string>(Directory.GetFiles(sourcePath));
                    files.ForEach(c =>
                    {
                        string destFile = Path.Combine(new string[] { destPath, Path.GetFileName(c) });
                        //覆盖模式  
                        if (File.Exists(destFile))
                        {
                            File.Delete(destFile);
                        }
                        File.Move(c, destFile);
                    });
                    //获得源文件下所有目录文件  
                    List<string> folders = new List<string>(Directory.GetDirectories(sourcePath));
    
                    folders.ForEach(c =>
                    {
                        string destDir = Path.Combine(new string[] { destPath, Path.GetFileName(c) });
                        //Directory.Move必须要在同一个根目录下移动才有效,不能在不同卷中移动。  
                        //Directory.Move(c, destDir);  
    
                        //采用递归的方法实现  
                        MoveFolder(c, destDir);
                    });
                }
                else
                {
           
    Move

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-05-20
  • 2021-07-03
  • 2021-12-18
  • 2021-12-27
  • 2021-07-03
猜你喜欢
  • 2021-12-16
  • 2022-12-23
  • 2022-12-23
  • 2021-06-19
  • 2021-08-29
  • 2022-12-23
相关资源
相似解决方案