一、将A路径下所有文件及文件夹,移动到一个新的路径中,并删除历史文件夹
点击查看代码
/// <summary>
/// 将历史文件夹移动到新路径中
/// </summary>
/// <param name="oldDirPath">历史文件夹路径</param>
/// <param name="newDirPath">新路径</param>
/// <returns>返回信息</returns>
public static string MoveOldDirToNewPath(string oldDirPath, string newDirPath)
{
string retMsg = "";
try
{
bool status = MoveDirToSpecPath(oldDirPath, newDirPath, out string msg);
if (status)
{
Directory.Delete(oldDirPath);
retMsg = "已完成文件夹的移动!";
}
else
{
retMsg = "移动文件夹失败!";
}
}
catch (Exception ex)
{
retMsg = $"移动文件夹异常:{ex.ToString()}";
}
return retMsg;
}
/// <summary>
/// 移动文件到指定位置
/// </summary>
/// <param name="oldDirPath">历史文件</param>
/// <param name="newDirPath">新位置文件</param>
/// <param name="msg">返回消息</param>
/// <returns>返回状态</returns>
public static bool MoveDirToSpecPath(string oldDirPath, string newDirPath, out string msg)
{
msg = "";
bool status = false;
try
{
if (Directory.Exists(oldDirPath))
{
if (!Directory.Exists(newDirPath))
{
Directory.CreateDirectory(newDirPath);
}
//拷贝文件到指定位置
foreach (string file in Directory.GetFiles(oldDirPath))
{
FileInfo fileInfo = new FileInfo(file);
fileInfo.MoveTo($"{newDirPath}/{fileInfo.Name}");
}
//拷贝文件夹到指定位置
foreach (string dir in Directory.GetDirectories(oldDirPath))
{
DirectoryInfo dirInfo = new DirectoryInfo(dir);
if (MoveDirToSpecPath(dir, $"{newDirPath}/{dirInfo.Name}", out msg) == false)
{
status = false;
}
}
status = true;
}
}
catch (Exception ex)
{
status = false;
msg = $"将历史路径所有文件及文件夹,移动到新路劲过程出现异常:{ex.ToString()}";
}
return status;
}
备注:
1.本功能是在Windows10系统下进行测试的
2.使用的是.Net Fromwork4.5~4.8框架