目录
第一章、简介
本篇博客,记录对文件、文件夹的日常拷贝、查找、删除等等功能。
第二章、文件拷贝
Copy一个文件夹的所有内容到另一个文件夹
参考:
https://blog.csdn.net/jhoneyan/article/details/52689146
注意该程序,一直在执行递归操作
注意该程序,一直在执行递归操作
注意该程序,一直在执行递归操作
source code(实测过,可以用):
#region 将文件夹拷贝到另一个文件夹
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Messaging;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace test
{
class Program
{
static void Main(string[] args)
{
string pLocalFilePath = @"C:\Users\lanmage2\Desktop\aaaa";//要复制的文件路径
string pSaveFilePath = @"C:\Users\lanmage2\Desktop\bbbb";//指定存储的路径
CopyDirectory(pLocalFilePath, pSaveFilePath);
}
/// <summary>
/// 复制文件夹中的所有内容
/// </summary>
/// <param name="sourceDirPath">源文件夹目录</param>
/// <param name="saveDirPath">指定文件夹目录</param>
public static void CopyDirectory(string sourceDirPath, string saveDirPath)
{
try
{
//如果指定的存储路径不存在,则创建该存储路径
if (!Directory.Exists(saveDirPath))
{
//创建
Directory.CreateDirectory(saveDirPath);
}
//获取源路径文件的名称
string[] files = Directory.GetFiles(sourceDirPath);
//遍历子文件夹的所有文件。
foreach (string file in files)
{
string pFilePath = saveDirPath + "\\" + Path.GetFileName(file);
if (File.Exists(pFilePath))
continue;
File.Copy(file, pFilePath, true);
}
string[] dirs = Directory.GetDirectories(sourceDirPath);
//递归,遍历文件夹
foreach (string dir in dirs)
{
CopyDirectory(dir, saveDirPath + "\\" + Path.GetFileName(dir));
}
}
catch (Exception ex)
{
}
}
}
}
#endregion
第三章、文件删除
/// <summary>
/// 删除指定文件夹下的所有文件,但不删除文件夹
/// </summary>
/// <param name="strFolderPath"></param>
public void DeleteFolderFileFunc(string strFolderPath)
{
try
{
DirectoryInfo dyInfo = new DirectoryInfo(strFolderPath);
foreach (FileInfo feInfo in dyInfo.GetFiles())
{
判断文件日期是否小于今天,是则删除
//if (feInfo.CreationTime < DateTime.Today)
// feInfo.Delete();
feInfo.Delete();
}
}
catch (Exception ex)
{
//log.WriteErrorLogFunc("FileManagement.cs::DeleteFolderFileFunc()——" + "删除指定文件夹下的所有文件发生错误:" + ex.ToString() + "\n\n");
}
}
/// <summary>
/// 删除指定文件夹
/// </summary>
/// <param name="strFolderPath"></param>
public void DeleteFolderFunc(string strFolderPath)
{
try
{
if (Directory.Exists(strFolderPath))
{
Directory.Delete(strFolderPath, true);
}
}
catch (Exception ex)
{
//log.WriteErrorLogFunc("FileManagement.cs::DeleteFolderFunc()——" + "删除指定文件夹发生错误:" + ex.ToString() + "\n\n");
}
}