遍歷文件夾的子文件夾下的所有文件,將上個月的文件集中到一起,然互壓縮,並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;
}
}