C#剪切、复制、删除、文件操作

1、剪切、复制

  private void CopyOrRemoveFile()
        {
            string srcFolder = "D:\\ABC";
            string destFolder = "D:\\ABC\\back\\" + DateTime.Now.ToString("yyyy-MM-dd");

            if (Directory.Exists(destFolder) == false)
            {
                Directory.CreateDirectory(destFolder);
            }

            DirectoryInfo directoryInfo = new DirectoryInfo(srcFolder);
            FileInfo[] files = directoryInfo.GetFiles();

            foreach (FileInfo file in files) // Directory.GetFiles(srcFolder)
            {
                if (file.Extension == ".jpg")
                {
                    file.MoveTo(Path.Combine(destFolder, file.Name)); //复制 ,剪切的话file.MoveTo();file.CopyTo是拷贝到另外一个文件夹
                    //file.Delete();
                }
            }
        }

2、删除

  private void DeleteLog(string filepath)
        {
            DirectoryInfo dir = new DirectoryInfo(filepath);
            FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();  //返回目录中所有文件和子目录
            foreach (FileSystemInfo i in fileinfo)
            {
                if (i is DirectoryInfo)            //判断是否文件夹
                {
                    DirectoryInfo subdir = new DirectoryInfo(i.FullName);
                    subdir.Delete(true);          //删除子目录和文件
                }
                else
                {
                    File.Delete(i.FullName);      //删除指定文件
                }
            }
        }

你可能感兴趣的:(C#)