ZIP压缩文件夹中上个月的文件,并将备份文件拷贝到服务器
遍历文件夹的子文件夹下的所有文件,将上个月的文件集中到一起,然互压缩,并copy到服务器的映射磁盘。
static void Main(string[] args)
{
//原始文件存放的位置
DirectoryInfo theFolder = new DirectoryInfo(@"E:\TestFloder");
//将文件拷贝到该文件夹下
string targetPath = @"D:\test";
DirectoryInfo[] dirInfo = theFolder.GetDirectories();
//遍历文件夹下的子文件夹
foreach (DirectoryInfo folder in dirInfo)
{
FileInfo[] filesInfo = folder.GetFiles();
//遍历子文件夹下的文件
foreach (FileInfo file in filesInfo)
{
//将上个月的文件拷贝到
if (file.CreationTime.ToShortDateString().Equals(DateTime.Now.AddMonths(-1).ToShortDateString()))
{
if (!CopyFile(file, targetPath))
{
//log 复制文件失败
}
else
{
file.Delete();
}
}
}
}
string zipFilePath = @"D:\" + DateTime.Now.AddMonths(-1).ToString("yyyyMMdd") + ".zip";
string remotePath = @"\\127.1.0.0" + @"D:\" + DateTime.Now.AddMonths(-1).ToString("yyyyMMdd") + ".zip";
if (!ZipFiles(targetPath, zipFilePath))
{
//压缩文件失败
}
else
{
//压缩文件成功
//将压缩后的文件拷贝到映射的服务器磁盘
if (!CopyFile(zipFilePath, remotePath))
{
//Copy失败
}
else
{
//copy成功
//删除原有的
File.Delete(zipFilePath);
}
}
}
/// <summary>
/// 移动文件到指定目录
/// </summary>
/// <param name="file">文件</param>
/// <param name="targetPath">目标路径</param>
/// <returns></returns>
public static bool CopyFile(FileInfo file, string targetPath)
{
try
{
if (!Directory.Exists(targetPath))
{
Directory.CreateDirectory(targetPath);
}
targetPath = targetPath + @"\" + file.Name;
File.Copy(file.FullName, targetPath, true);
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// 移动文件到指定目录
/// </summary>
/// <param name="filePath"></param>
/// <param name="targetPath"></param>
/// <returns></returns>
public static bool CopyFile(string filePath, string targetPath)
{
try
{
File.Copy(filePath, targetPath, true);
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// 压缩文件
/// </summary>
/// <param name="folderPath">被压缩文件夹路径</param>
/// <param name="zipPath">压缩文件路径</param>
/// <returns></returns>
public static bool ZipFiles(string folderPath, string zipPath)
{
try
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
//软件7Z的安装目录
process.StartInfo.FileName = @"D:\Program Files\7-Zip\7z.exe";
process.StartInfo.Arguments = string.Format(" a -tzip {0} {1}", zipPath, folderPath);
process.Start();
//一定要等待完成后,才能删除。
process.WaitForExit();
//删除文件夹下文件
DeleteFiles(folderPath);
return true;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 删除文件夹下文件
/// </summary>
/// <param name="folderPath">文件夹路径</param>
public static void DeleteFiles(string folderPath)
{
try
{
DirectoryInfo folder = new DirectoryInfo(folderPath);
FileInfo[] filesInfo = folder.GetFiles();
foreach (FileInfo file in filesInfo)
{
File.Delete(file.FullName);
}
//log 删除文件夹下文件成功
}
catch (Exception ex)
{
//log 删除文件夹下文件失败
throw ex;
}
}