C#将文件复制到指定文件夹并整理
程序员文章站
2023-08-17 19:48:39
下面是在c#中将文件复制(剪切是先复制再删除)到指定的路径,并按日期归档的一个简单实例。值得注意的2点是:
1)文件的路径是关键,程序中使用双斜杠\\
2)文件和文件夹...
下面是在c#中将文件复制(剪切是先复制再删除)到指定的路径,并按日期归档的一个简单实例。值得注意的2点是:
1)文件的路径是关键,程序中使用双斜杠\\
2)文件和文件夹的区别
private void dowork() { string dir="d:\\abc" //创建备份文件夹,按时间命名 string bakdir = dir + "\\bak\\" + datetime.now.tostring("yyyy-mm-dd"); if (directory.exists(bakdir) == false){ directory.createdirectory(bakdir); } string[] files = directory.getfiles(dir); if (files.length != 0) { foreach (string file in files) { fileinfo fileinfo = new fileinfo(file); try{ string filename = file.replace(dir, ""); //备份文件 file.copy(file,path.combine(bakdir,filename)); file.delete(file); } } }
附上其他网友的实现方法:
private void copydir(string srcpath, string aimpath) { try { // 检查目标目录是否以目录分割字符结束如果不是则添加 if (aimpath[aimpath.length - 1] != system.io.path.directoryseparatorchar) { aimpath += system.io.path.directoryseparatorchar; } // 判断目标目录是否存在如果不存在则新建 if (!system.io.directory.exists(aimpath)) { system.io.directory.createdirectory(aimpath); } // 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组 // 如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法 // string[] filelist = directory.getfiles(srcpath); string[] filelist = system.io.directory.getfilesystementries(srcpath); // 遍历所有的文件和目录 foreach (string file in filelist) { // 先当作目录处理如果存在这个目录就递归copy该目录下面的文件 if(system.io.directory.exists(file)) { copydir(file, aimpath + system.io.path.getfilename(file)); } // 否则直接copy文件 else { system.io.file.copy(file, aimpath + system.io.path.getfilename(file),true); } } } catch(exception e) { throw; } } }
完全可以不用递归实现,用广度优先算法可以节省栈空间
using system; using system.io; using system.collections; using system.collections.generic; string sourcepath=@"c:\sourcedir"; queue<filesysteminfo> copyfolders = new queue<filesysteminfo>(new directoryinfo(sourcepath).getfilesysteminfos()); string copytopath = @"c:\targetdir"; copytopath = (copytopath.lastindexof(path.directoryseparatorchar) == copytopath.length - 1) ? copytopath : (copytopath+path.directoryseparatorchar) + path.getfilename(sourcepath); directory.createdirectory(copytopath); while (copyfolders.count>0) { filesysteminfo atom = opyfolders.dequeue(); fileinfo file = atom as fileinfo; if (file == null) { directoryinfo directory = atom as directoryinfo; directory.createdirectory(directory.fullname.replace(sourcepath,copytopath)); foreach (filesysteminfo fi in directory.getfilesysteminfos()) copyfolders.enqueue(fi); } else file.copyto(file.fullname.replace(sourcepath,copytopath)); }
以上所述就是本文的全部内容了,希望大家能够喜欢。
上一篇: 桂枝人参汤的功效你知道多少
下一篇: 你知道上火吃什么菜吗