440 lines
19 KiB
C#
440 lines
19 KiB
C#
using System;
|
||
using System.Collections.Generic;
|
||
using System.Globalization;
|
||
using System.IO;
|
||
using System.Linq;
|
||
using System.Security.AccessControl;
|
||
using System.Security.Cryptography;
|
||
using System.Text;
|
||
|
||
namespace RunUpdater.Lib
|
||
{
|
||
public class FileHelper
|
||
{
|
||
public enum FilePower
|
||
{
|
||
FullControl = 0,
|
||
ReadOnly = 1,
|
||
Write = 2,
|
||
Modify = 3
|
||
}
|
||
|
||
/// <summary>
|
||
/// 计算指定文件MD5
|
||
/// </summary>
|
||
/// <param name="FilePath">文件路径</param>
|
||
/// <returns>返回MD5</returns>
|
||
public static string GetMD5ByMD5CryptoService(string FilePath)
|
||
{
|
||
try
|
||
{
|
||
FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
|
||
MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider();
|
||
byte[] buffer = md5Provider.ComputeHash(fs);
|
||
string resule = BitConverter.ToString(buffer);
|
||
resule = resule.Replace("-", "");
|
||
md5Provider.Clear();
|
||
fs.Close();
|
||
return resule;
|
||
}
|
||
catch
|
||
{
|
||
return "";
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
///计算指定大文件MD5
|
||
/// </summary>
|
||
/// <param name="FilePath">文件地址</param>
|
||
/// <returns>返回MD5</returns>
|
||
public static string GetMD5ByHashAlgorithm(string FilePath)
|
||
{
|
||
try
|
||
{
|
||
int bufferSize = 1024 * 16;//自定义缓冲区大小16K
|
||
byte[] buffer = new byte[bufferSize];
|
||
Stream inputStream = File.Open(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
|
||
HashAlgorithm hashAlgorithm = new MD5CryptoServiceProvider();
|
||
int readLength = 0;//每次读取长度
|
||
var output = new byte[bufferSize];
|
||
while ((readLength = inputStream.Read(buffer, 0, buffer.Length)) > 0)
|
||
{
|
||
//计算MD5
|
||
hashAlgorithm.TransformBlock(buffer, 0, readLength, output, 0);
|
||
}
|
||
//完成最后计算,必须调用(由于上一部循环已经完成所有运算,所以调用此方法时后面的两个参数都为0)
|
||
hashAlgorithm.TransformFinalBlock(buffer, 0, 0);
|
||
string md5 = BitConverter.ToString(hashAlgorithm.Hash);
|
||
hashAlgorithm.Clear();
|
||
inputStream.Close();
|
||
md5 = md5.Replace("-", "");
|
||
return md5;
|
||
}
|
||
catch
|
||
{
|
||
return "";
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 字节转换为GB、MB、KB、B
|
||
/// </summary>
|
||
/// <param name="byteSize">待转换字节数值</param>
|
||
/// <returns>返回转换结果GB、MB、KB、B</returns>
|
||
public static string ConvertSize(long byteSize)
|
||
{
|
||
int unit = 1024;
|
||
|
||
if (byteSize < unit) return byteSize + " B";
|
||
|
||
int exp = (int)(Math.Log(byteSize) / Math.Log(unit));
|
||
|
||
return $"{byteSize / Math.Pow(unit, exp):F2}{"KMGTPE"[exp - 1]}B";
|
||
}
|
||
|
||
#region 文件操作
|
||
|
||
/// <summary>
|
||
/// 删除指定目录下的所有文件及文件夹
|
||
/// </summary>
|
||
/// <param name="strPath">待删除目录</param>
|
||
/// <param name="isReservedDir">是否保留目录</param>
|
||
/// <returns>删除结果</returns>
|
||
public static bool DeleteDir(string strPath, bool isReservedDir = true)
|
||
{
|
||
try
|
||
{
|
||
// 清除空格
|
||
strPath = @strPath.Trim().ToString();
|
||
// 判断文件夹是否存在
|
||
if (Directory.Exists(strPath))
|
||
{
|
||
// 获得文件夹数组
|
||
string[] strDirs = Directory.GetDirectories(strPath);
|
||
// 获得文件数组
|
||
string[] strFiles = Directory.GetFiles(strPath);
|
||
// 遍历所有子文件夹
|
||
foreach (string strFile in strFiles)
|
||
{
|
||
// 删除文件
|
||
File.Delete(strFile);
|
||
}
|
||
// 遍历所有文件
|
||
foreach (string strdir in strDirs)
|
||
{
|
||
// 删除文件夹
|
||
Directory.Delete(strdir, true);
|
||
}
|
||
if (!isReservedDir)
|
||
{
|
||
Directory.Delete(strPath);
|
||
}
|
||
}
|
||
// 成功
|
||
return true;
|
||
}
|
||
catch (Exception) // 异常处理
|
||
{
|
||
// 失败
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 删除指定目录下的指定后缀名的文件
|
||
/// </summary>
|
||
/// <param name="directory">要删除的文件所在的目录,是绝对目录,如d:\temp</param>
|
||
/// <param name="masks">要删除的文件的后缀名的一个数组,比如masks中包含了.cs,.vb,.c这三个元素</param>
|
||
/// <param name="searchSubdirectories">表示是否需要递归删除,即是否也要删除子目录中相应的文件</param>
|
||
/// <param name="ignoreHidden">表示是否忽略隐藏文件</param>
|
||
/// <param name="deletedFileCount">表示总共删除的文件数</param>
|
||
public static bool DeleteFiles(string directory, string[] masks, bool searchSubdirectories, bool ignoreHidden, ref int deletedFileCount)
|
||
{
|
||
try
|
||
{
|
||
//先删除当前目录下指定后缀名的所有文件
|
||
foreach (string file in Directory.GetFiles(directory, "*.*"))
|
||
{
|
||
if (!(ignoreHidden && (File.GetAttributes(file) & FileAttributes.Hidden) == FileAttributes.Hidden))
|
||
{
|
||
foreach (string mask in masks)
|
||
{
|
||
if (Path.GetExtension(file) == mask)
|
||
{
|
||
File.Delete(file);
|
||
deletedFileCount++;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
//如果需要对子目录进行处理,则对子目录也进行递归操作
|
||
if (searchSubdirectories)
|
||
{
|
||
string[] childDirectories = Directory.GetDirectories(directory);
|
||
foreach (string dir in childDirectories)
|
||
{
|
||
if (!(ignoreHidden && (File.GetAttributes(dir) & FileAttributes.Hidden) == FileAttributes.Hidden))
|
||
{
|
||
DeleteFiles(dir, masks, searchSubdirectories, ignoreHidden, ref deletedFileCount);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
catch (Exception)
|
||
{
|
||
return false;
|
||
}
|
||
return true;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 删除指定目录下的指定后缀名的文件
|
||
/// </summary>
|
||
/// <param name="directory">要删除的文件所在的目录,是绝对目录,如d:\temp</param>
|
||
/// <param name="masks">要删除的文件的后缀名的一个数组,比如masks中包含了.cs,.vb,.c这三个元素</param>
|
||
/// <param name="searchSubdirectories">表示是否需要递归删除,即是否也要删除子目录中相应的文件</param>
|
||
/// <param name="ignoreHidden">表示是否忽略隐藏文件</param>
|
||
/// /// <param name="deletedFileCount">表示总共删除的文件数</param>
|
||
public static void DeleteFiles(string directory, string[] masks, bool searchSubdirectories, bool ignoreHidden, int delDay, ref int deletedFileCount)
|
||
{
|
||
//先删除当前目录下指定后缀名的所有文件
|
||
foreach (string file in Directory.GetFiles(directory, "*.*"))
|
||
{
|
||
if (!(ignoreHidden && (File.GetAttributes(file) & FileAttributes.Hidden) == FileAttributes.Hidden))
|
||
{
|
||
foreach (string mask in masks)
|
||
{
|
||
if (Path.GetExtension(file) == mask)
|
||
{
|
||
FileInfo _FileInfo = new FileInfo(file);
|
||
if (_FileInfo.LastWriteTime < DateTime.Now.Date.AddDays(-1 * delDay))
|
||
{
|
||
_FileInfo.Delete();
|
||
deletedFileCount++;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
//如果需要对子目录进行处理,则对子目录也进行递归操作
|
||
if (searchSubdirectories)
|
||
{
|
||
string[] childDirectories = Directory.GetDirectories(directory);
|
||
foreach (string dir in childDirectories)
|
||
{
|
||
if (!(ignoreHidden && (File.GetAttributes(dir) & FileAttributes.Hidden) == FileAttributes.Hidden))
|
||
{
|
||
DeleteFiles(dir, masks, searchSubdirectories, ignoreHidden, delDay, ref deletedFileCount);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 拷贝文件至指定目标目录
|
||
/// </summary>
|
||
/// <param name="sourcePath">源文件目录(@"~\labs\oldlab")</param>
|
||
/// <param name="savePath">保存的目标目录(@"~\labs\newlab")</param>
|
||
/// <returns>返回:true-拷贝成功;false:拷贝失败</returns>
|
||
public static bool CopyOldFilesToNewFiles(string sourcePath, string savePath)
|
||
{
|
||
if (!Directory.Exists(savePath))
|
||
{
|
||
Directory.CreateDirectory(savePath);
|
||
}
|
||
try
|
||
{
|
||
string[] labDirs = Directory.GetDirectories(sourcePath);//目录
|
||
string[] labFiles = Directory.GetFiles(sourcePath);//文件
|
||
if (labFiles.Length > 0)
|
||
{
|
||
for (int i = 0; i < labFiles.Length; i++)
|
||
{
|
||
if (Path.GetFileName(labFiles[i]) != "lpk.dll")//排除.lab文件
|
||
{
|
||
if (labFiles[i].EndsWith(".rar", true, null))
|
||
{
|
||
File.Copy(sourcePath + "\\" + Path.GetFileName(labFiles[i]), savePath + "\\" +
|
||
Path.GetFileName(labFiles[i].Substring(0, labFiles[i].ToLower().LastIndexOf(".rar"))), true);
|
||
}
|
||
else
|
||
{
|
||
File.Copy(sourcePath + "\\" + Path.GetFileName(labFiles[i]), savePath + "\\" + Path.GetFileName(labFiles[i]), true);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
if (labDirs.Length > 0)
|
||
{
|
||
for (int j = 0; j < labDirs.Length; j++)
|
||
{
|
||
Directory.GetDirectories(sourcePath + "\\" + Path.GetFileName(labDirs[j]));
|
||
//递归调用
|
||
CopyOldFilesToNewFiles(sourcePath + "\\" + Path.GetFileName(labDirs[j]), savePath + "\\" + Path.GetFileName(labDirs[j]));
|
||
}
|
||
}
|
||
}
|
||
catch (Exception)
|
||
{
|
||
return false;
|
||
}
|
||
return true;
|
||
}
|
||
/// <summary>
|
||
/// 拷贝文件至指定目标目录
|
||
/// </summary>
|
||
/// <param name="sourcePath">源文件目录(@"~\labs\oldlab")</param>
|
||
/// <param name="savePath">保存的目标目录(@"~\labs\newlab")</param>
|
||
/// <param name="Extension">保存的目标后缀</param>
|
||
/// <returns>返回:true-拷贝成功;false:拷贝失败</returns>
|
||
public static bool CopyOldFilesToNewFiles(string sourcePath, string savePath, string Extension = "")
|
||
{
|
||
if (!Directory.Exists(savePath))
|
||
{
|
||
Directory.CreateDirectory(savePath);
|
||
}
|
||
try
|
||
{
|
||
string[] labDirs = Directory.GetDirectories(sourcePath);//目录
|
||
string[] labFiles = Directory.GetFiles(sourcePath);//文件
|
||
if (labFiles.Length > 0)
|
||
{
|
||
for (int i = 0; i < labFiles.Length; i++)
|
||
{
|
||
if (Path.GetFileName(labFiles[i]) != "lpk.dll")//排除lpk.dll文件
|
||
{
|
||
if (labFiles[i].EndsWith(Extension))
|
||
{
|
||
File.Copy(sourcePath + "\\" + Path.GetFileName(labFiles[i]), savePath + "\\" +
|
||
Path.GetFileName(labFiles[i]), true);
|
||
}
|
||
else
|
||
{
|
||
File.Copy(sourcePath + "\\" + Path.GetFileName(labFiles[i]), savePath + "\\" + Path.GetFileName(labFiles[i]) + Extension, true);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
if (labDirs.Length > 0)
|
||
{
|
||
for (int j = 0; j < labDirs.Length; j++)
|
||
{
|
||
Directory.GetDirectories(sourcePath + "\\" + Path.GetFileName(labDirs[j]));
|
||
//递归调用
|
||
CopyOldFilesToNewFiles(sourcePath + "\\" + Path.GetFileName(labDirs[j]), savePath + "\\" + Path.GetFileName(labDirs[j]), Extension);
|
||
}
|
||
}
|
||
}
|
||
catch (Exception)
|
||
{
|
||
return false;
|
||
}
|
||
return true;
|
||
}
|
||
/// <summary>
|
||
/// 返回指定目录下的所有文件信息
|
||
/// </summary>
|
||
/// <param name="strDirectory"></param>
|
||
/// <returns></returns>
|
||
public List<FileInfo> GetAllFilesInDirectory(string strDirectory)
|
||
{
|
||
//判断文件夹是否存在,不存在则退出
|
||
if (!Directory.Exists(strDirectory))
|
||
return null;
|
||
|
||
List<FileInfo> listFiles = new List<FileInfo>(); //保存所有的文件信息
|
||
DirectoryInfo directory = new DirectoryInfo(strDirectory);
|
||
DirectoryInfo[] directoryArray = directory.GetDirectories();
|
||
FileInfo[] fileInfoArray = directory.GetFiles();
|
||
if (fileInfoArray.Length > 0) listFiles.AddRange(fileInfoArray);
|
||
foreach (DirectoryInfo _directoryInfo in directoryArray)
|
||
{
|
||
DirectoryInfo directoryA = new DirectoryInfo(_directoryInfo.FullName);
|
||
DirectoryInfo[] directoryArrayA = directoryA.GetDirectories();
|
||
FileInfo[] fileInfoArrayA = directoryA.GetFiles();
|
||
if (fileInfoArrayA.Length > 0) listFiles.AddRange(fileInfoArrayA);
|
||
GetAllFilesInDirectory(_directoryInfo.FullName);//递归遍历
|
||
}
|
||
return listFiles;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 获取所有目录即子目录下的文件总字节大小
|
||
/// </summary>
|
||
/// <param name="listFileInfo">返回指定目录下的所有文件信息</param>
|
||
/// <returns>返回值</returns>
|
||
private static long GetUpdateSize(List<FileInfo> listFileInfo)
|
||
{
|
||
long len = 0;
|
||
if (listFileInfo != null)
|
||
{
|
||
foreach (FileInfo fileInfo in listFileInfo)
|
||
{
|
||
if (fileInfo.Name != "lpk.dll")
|
||
{
|
||
len += fileInfo.Length;
|
||
}
|
||
}
|
||
}
|
||
return len;
|
||
}
|
||
#endregion
|
||
|
||
/// <summary>
|
||
/// 为创建的临时文件分配权限
|
||
/// </summary>
|
||
/// <param name="pathname"></param>
|
||
/// <param name="username"></param>
|
||
/// <param name="power"></param>
|
||
public static void AddpathPower(string pathname, string username, string power)
|
||
{
|
||
DirectoryInfo dirinfo = new DirectoryInfo(pathname);
|
||
if ((dirinfo.Attributes & FileAttributes.ReadOnly) != 0)
|
||
{
|
||
dirinfo.Attributes = FileAttributes.Normal;
|
||
}
|
||
//取得访问控制列表
|
||
DirectorySecurity dirsecurity = dirinfo.GetAccessControl();
|
||
switch (power)
|
||
{
|
||
case "FullControl":
|
||
dirsecurity.AddAccessRule(new FileSystemAccessRule(username, FileSystemRights.FullControl,
|
||
InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
|
||
break;
|
||
case "ReadOnly":
|
||
dirsecurity.AddAccessRule(new FileSystemAccessRule(username, FileSystemRights.Read, AccessControlType.Allow));
|
||
break;
|
||
case "Write":
|
||
dirsecurity.AddAccessRule(new FileSystemAccessRule(username, FileSystemRights.Write, AccessControlType.Allow));
|
||
break;
|
||
case "Modify":
|
||
dirsecurity.AddAccessRule(new FileSystemAccessRule(username, FileSystemRights.Modify, AccessControlType.Allow));
|
||
break;
|
||
}
|
||
}
|
||
/// <summary>
|
||
///为文件夹添加users,everyone用户组的完全控制权限
|
||
/// </summary>
|
||
/// <param name="dirPath"></param>
|
||
public static void AddSecurityControll2Folder(string dirPath)
|
||
{
|
||
//获取文件夹信息
|
||
DirectoryInfo dir = new DirectoryInfo(dirPath);
|
||
//获得该文件夹的所有访问权限
|
||
DirectorySecurity dirSecurity = dir.GetAccessControl(AccessControlSections.All);
|
||
//设定文件ACL继承
|
||
InheritanceFlags inherits = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
|
||
//添加ereryone用户组的访问权限规则 完全控制权限
|
||
FileSystemAccessRule everyoneFileSystemAccessRule = new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
|
||
//添加Users用户组的访问权限规则 完全控制权限
|
||
FileSystemAccessRule usersFileSystemAccessRule = new FileSystemAccessRule("Users", FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
|
||
bool isModified = false;
|
||
dirSecurity.ModifyAccessRule(AccessControlModification.Add, everyoneFileSystemAccessRule, out isModified);
|
||
dirSecurity.ModifyAccessRule(AccessControlModification.Add, usersFileSystemAccessRule, out isModified);
|
||
//设置访问权限
|
||
dir.SetAccessControl(dirSecurity);
|
||
}
|
||
}
|
||
}
|