文件操作相关api
1.File.Delete(path); 删除文件
解读:这个静态方法 的path 必须精确到文件,比如 var path = @"D:\20220801\222\222.txt"; 这样才能删除成功
如果要删除某个文件夹下所有子文件夹和文件 该怎么删除?
DirectoryInfo dir = new DirectoryInfo(path);
dir.Delete(true);
这种就可以删除该文件夹下的所有子文件夹和文件
2.复制文件:下边这种复制方式很有局限性,只能复制到具体文件
public void CopyFile(string fromPath,string toPath)
{
if (File.Exists(toPath)) //首先判断文件是否存在(如果文件存在,直接复制会出现错误)
{
File.Delete(toPath); //删除文件
}
File.Copy(fromPath,toPath);
}
如果要复制整个文件夹下的所有子文件夹和文件 ,那么就需要用到递归来做
//首先判断是否有该路径
if(Directory.Exists(srcPath)&&Directory.Exists(destPath)) { CopyDirectory(srcPath,destPath);
}
//然后写个递归的方法
public static void CopyDirectory(string srcPath, string destPath) { try { DirectoryInfo dir = new DirectoryInfo(srcPath); FileSystemInfo[] fileinfo = dir.GetFileSystemInfos(); //获取目录下(不包含子目录)的文件和子目录 foreach (FileSystemInfo i in fileinfo) { if (i is DirectoryInfo) //判断是否文件夹 { if (!Directory.Exists(destPath+"\\"+i.Name)) { Directory.CreateDirectory(destPath + "\\" + i.Name); //目标目录下不存在此文件夹即创建子文件夹 } CopyDirectory(i.FullName, destPath + "\\" + i.Name); //递归调用复制子文件夹 } else { File.Copy(i.FullName, destPath + "\\" + i.Name,true); //不是文件夹即复制文件,true表示可以覆盖同名文件 } } } catch (Exception e) { throw; } }
这样就可以把整个文件夹下的相关子文件夹,文件,全部都复制到新文件夹里去 了
这些属于常用的,其他不常用的,可以现百度
posted on 2022-08-02 10:35 泰坦尼克号上的活龙虾 阅读(51) 评论(0) 收藏 举报