using System; using System.Configuration; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; namespace Common.system { /// /// 文件工具公共方法 /// 创建人:赵耀 /// 创建时间:2018年11月6日 /// public static class FileToolsCommon { #region 获取文件的绝对路径 /// /// 获取文件的绝对路径 /// /// 相对路径 /// public static string GetFileAbsolutePath(string Path = "") { try { if (!string.IsNullOrWhiteSpace(Path)) { Path = Path.Replace("\\", "/"); if (Path != "/") { if (Path.Substring(1, 1) == ":") { return Path; } if (Path.Substring(0, 1) != "/") { Path = "/" + Path; } } } string AbsolutePath = Application.StartupPath.ToString().Replace("\\", "/") + Path; return AbsolutePath; } catch (Exception) { return Path; } } /// /// 获取合法路径 结尾带/ /// /// public static string GetLegalPath(string FilePath) { FilePath = System.IO.Path.Combine(FilePath.Replace("\\", "/")); FilePath += (FilePath.Substring(FilePath.Length - 1, 1) == "/" ? "" : "/"); return FilePath; } #endregion #region 检测路径是否合法 /// /// 检测路径是否合法 /// /// 绝对路径 /// 返回错误 /// public static bool IsLegalPath(string FilePathName, out string ErrMessage) { string FilePath; string FileName; ErrMessage = ""; try { FilePathName = GetLegalPath(FilePathName); FilePath = GetDirectoryName(FilePathName); FileName = GetIOFileName(FilePathName); } catch (Exception) { ErrMessage = "路径或文件名不合法!"; return false; } Regex regex = new Regex(@"^([a-zA-Z]:\\)?[^\/\:\*\?\""\<\>\|\,]*$"); Match m = regex.Match(FilePath); if (!m.Success) { ErrMessage = "非法的文件保存路径!"; return false; } if (!string.IsNullOrWhiteSpace(FileName)) { regex = new Regex(@"^[^\/\:\*\?\""\<\>\|\,]+$"); m = regex.Match(FileName); if (!m.Success) { ErrMessage = "非法的文件名!文件名中包含\\ / : * ? \" < > |等字符!"; return false; } } return true; } #endregion #region 检测指定目录是否存在 /// /// 检测指定目录是否存在 /// /// 目录的绝对路径 public static bool IsExistDirectory(string directoryPath) { return Directory.Exists(directoryPath); } #endregion #region 检测指定文件是否存在 /// /// 检测指定文件是否存在,如果存在则返回true。 /// /// 文件的绝对路径 public static bool IsExistFile(string filePath) { return File.Exists(filePath); } #endregion #region 检测指定目录是否为空 /// /// 检测指定目录是否为空 /// /// 指定目录的绝对路径 public static bool IsEmptyDirectory(string directoryPath) { try { //判断是否存在文件 string[] fileNames = GetFileNames(directoryPath); if (fileNames.Length > 0) { return false; } //判断是否存在文件夹 string[] directoryNames = GetDirectories(directoryPath); return directoryNames.Length <= 0; } catch { return false; } } #endregion #region 检测指定目录中是否存在指定的文件 /// /// 检测指定目录中是否存在指定的文件,若要搜索子目录请使用重载方法. /// /// 指定目录的绝对路径 /// 模式字符串,"*"代表0或N个字符,"?"代表1个字符。 /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。 public static bool Contains(string directoryPath, string searchPattern) { try { //获取指定的文件列表 string[] fileNames = GetFileNames(directoryPath, searchPattern, false); //判断指定文件是否存在 return fileNames.Length != 0; } catch { return false; } } /// /// 检测指定目录中是否存在指定的文件 /// /// 指定目录的绝对路径 /// 模式字符串,"*"代表0或N个字符,"?"代表1个字符。 /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。 /// 是否搜索子目录 public static bool Contains(string directoryPath, string searchPattern, bool isSearchChild) { try { //获取指定的文件列表 string[] fileNames = GetFileNames(directoryPath, searchPattern, isSearchChild); //判断指定文件是否存在 return fileNames.Length != 0; } catch { return false; } } #endregion #region 创建一个目录 /// /// 创建一个目录 /// /// 目录的绝对路径 public static void CreateDirectory(string directoryPath) { try { //如果目录不存在则创建该目录 if (!IsExistDirectory(directoryPath)) { Directory.CreateDirectory(directoryPath); } } catch (Exception ex) { throw new ApplicationException(ex.Message); //"请使用管理员权限运行!" } } #endregion #region 创建一个文件 /// /// 创建一个文件。 /// /// 文件的绝对路径 public static bool CreateFile(string filePath) { try { //如果文件不存在则创建该文件 if (!IsExistFile(filePath)) { //创建一个FileInfo对象 FileInfo file = new FileInfo(filePath); //创建文件 FileStream fs = file.Create(); //关闭文件流 fs.Close(); } } catch { return false; } return true; } /// /// 创建一个文件,并将字节流写入文件。 /// /// 文件的绝对路径 /// 二进制流数据 public static bool CreateFile(string filePath, byte[] buffer) { try { //如果文件不存在则创建该文件 if (!IsExistFile(filePath)) { //创建一个FileInfo对象 FileInfo file = new FileInfo(filePath); //创建文件 FileStream fs = file.Create(); //写入二进制流 fs.Write(buffer, 0, buffer.Length); //关闭文件流 fs.Close(); } } catch { return false; } return true; } #endregion #region 获取文本文件的行数 /// /// 获取文本文件的行数 /// /// 文件的绝对路径 public static int GetLineCount(string filePath) { //将文本文件的各行读到一个字符串数组中 string[] rows = File.ReadAllLines(filePath); //返回行数 return rows.Length; } #endregion #region 获取一个文件的长度 /// /// 获取一个文件的长度,单位为Byte /// /// 文件的绝对路径 public static long GetFileSize(string filePath) { //创建一个文件对象 FileInfo fi = new FileInfo(filePath); //获取文件的大小 return fi.Length; } /// /// 获取一个文件的长度,单位为KB /// /// 文件的路径 public static double GetFileSizeByKB(string filePath) { //创建一个文件对象 FileInfo fi = new FileInfo(filePath); //double size = fi.Length / 1024; double size = Math.Round((fi.Length / 1024.0), 2, MidpointRounding.AwayFromZero); //获取文件的大小 return size; } /// /// 获取一个文件的长度,单位为MB /// /// 文件的路径 public static double GetFileSizeByMB(string filePath) { //创建一个文件对象 FileInfo fi = new FileInfo(filePath); //double size = fi.Length / 1024 / 1024; double size = Math.Round((fi.Length / 1024.0 / 1024.0), 2, MidpointRounding.AwayFromZero); //获取文件的大小 return size; } #endregion #region 获取指定目录中的文件列表 /// /// 获取指定目录中所有文件列表 /// /// 指定目录的绝对路径 public static FileInfo[] GetFileInfos(string directoryPath, string files = null) { //如果目录不存在,则抛出异常 if (!IsExistDirectory(directoryPath)) { return null;//throw new FileNotFoundException(); } DirectoryInfo folder = new DirectoryInfo(directoryPath); FileInfo[] fileList; if (files == null) { fileList = folder.GetFiles(); } else { fileList = folder.GetFiles(files); } //获取文件列表 return fileList; } /// /// 获取指定目录中所有文件列表 /// /// 指定目录的绝对路径 public static string[] GetFileNames(string directoryPath) { //如果目录不存在,则抛出异常 if (!IsExistDirectory(directoryPath)) { return null;//throw new FileNotFoundException(); } //获取文件列表 return Directory.GetFiles(directoryPath); } /// /// 获取指定目录及子目录中所有文件列表 /// /// 指定目录的绝对路径 /// 模式字符串,"*"代表0或N个字符,"?"代表1个字符。 /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。 /// 是否搜索子目录 public static string[] GetFileNames(string directoryPath, string searchPattern, bool isSearchChild) { //如果目录不存在,则抛出异常 if (!IsExistDirectory(directoryPath)) { return null;//throw new FileNotFoundException(); } try { return Directory.GetFiles(directoryPath, searchPattern, isSearchChild ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly); } catch { return null; } } #endregion #region 获取指定目录中的子目录列表 /// /// 获取指定目录中所有子目录列表,若要搜索嵌套的子目录列表,请使用重载方法. /// /// 指定目录的绝对路径 public static string[] GetDirectories(string directoryPath) { try { return Directory.GetDirectories(directoryPath); } catch { return null; } } /// /// 获取指定目录及子目录中所有子目录列表 /// /// 指定目录的绝对路径 /// 模式字符串,"*"代表0或N个字符,"?"代表1个字符。 /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。 /// 是否搜索子目录 public static string[] GetDirectories(string directoryPath, string searchPattern, bool isSearchChild) { try { return Directory.GetDirectories(directoryPath, searchPattern, isSearchChild ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly); } catch { return null;//throw } } #endregion #region 向文本文件写入内容 /// /// 向文本文件中写入内容 /// /// 文件的绝对路径 /// 写入的内容 public static void WriteText(string filePath, string content) { //向文件写入内容 File.WriteAllText(filePath, content); } #endregion #region 向文本文件的尾部追加内容 /// /// 向文本文件的尾部追加内容 /// /// 文件的绝对路径 /// 写入的内容 public static void AppendText(string filePath, string content) { File.AppendAllText(filePath, content); } #endregion #region 将现有文件的内容复制到新文件中 /// /// 将源文件的内容复制到目标文件中 /// /// 源文件的绝对路径 /// 目标文件的绝对路径 public static void Copy(string sourceFilePath, string destFilePath) { File.Copy(sourceFilePath, destFilePath, true); } #endregion #region 将文件移动到指定目录 /// /// 将文件移动到指定目录 /// /// 需要移动的源文件的绝对路径 /// 移动到的目录的绝对路径 public static void Move(string sourceFilePath, string descDirectoryPath) { //获取源文件的名称 string sourceFileName = GetFileName(sourceFilePath); if (IsExistDirectory(descDirectoryPath)) { //如果目标中存在同名文件,则删除 if (IsExistFile(descDirectoryPath + "\\" + sourceFileName)) { DeleteFile(descDirectoryPath + "\\" + sourceFileName); } //将文件移动到指定目录 File.Move(sourceFilePath, descDirectoryPath + "\\" + sourceFileName); } } #endregion #region 将流读取到缓冲区中 /// /// 将流读取到缓冲区中 /// /// 原始流 public static byte[] StreamToBytes(Stream stream) { try { //创建缓冲区 byte[] buffer = new byte[stream.Length]; //读取流 stream.Read(buffer, 0, int.Parse(stream.Length.ToString())); //返回流 return buffer; } catch { return null; } finally { //关闭流 stream.Close(); } } #endregion #region 将文件读取到缓冲区中 /// /// 将文件读取到缓冲区中 /// /// 文件的绝对路径 public static byte[] FileToBytes(string filePath) { //获取文件的大小 long fileSize = GetFileSize(filePath); //创建一个临时缓冲区 byte[] buffer = new byte[fileSize]; //创建一个文件流 FileInfo fi = new FileInfo(filePath); FileStream fs = fi.Open(FileMode.Open); try { //将文件流读入缓冲区 fs.Read(buffer, 0, (int)fileSize); return buffer; } catch { return null; } finally { //关闭文件流 fs.Close(); } } /// /// 读取大文件用,读取文件前面指定长度字节数 /// /// 文件路径 /// 读取长度,单位字节 /// public static byte[] ReadBigFile(string filePath, int Length) { FileStream stream = new FileStream(filePath, FileMode.Open); byte[] buffer = new byte[Length]; //stream.Position = startIndex; stream.Read(buffer, 0, Length); stream.Close(); stream.Dispose(); return buffer; } /// /// 读取指定长度的流 /// /// 文件位置 /// 开始位置 /// 长度 /// public static byte[] ReadBigFileSpecifyLength(string filePath, long startIndex, int Length) { FileStream stream = new FileStream(filePath, FileMode.Open); if (startIndex + Length + 1 > stream.Length) { Length = (int)(stream.Length - startIndex); } byte[] buffer = new byte[Length]; stream.Position = startIndex; stream.Read(buffer, 0, Length); stream.Close(); stream.Dispose(); return buffer; } #endregion #region 将文件读取到字符串中 /// /// 将文件读取到字符串中 /// /// 文件的绝对路径 public static string FileToString(string filePath) { //return FileToString(filePath, Encoding.Default); return FileToString(filePath, Encoding.UTF8); } /// /// 将文件读取到字符串中 /// /// 文件的绝对路径 /// 字符编码 public static string FileToString(string filePath, Encoding encoding) { //创建流读取器 StreamReader reader = new StreamReader(filePath, encoding); try { //读取流 return reader.ReadToEnd(); } catch { return string.Empty; } finally { //关闭流读取器 reader.Close(); } } /// /// 读取大文件用,读取文件前面指定长度字节的字符串 /// /// 文件路径 /// 读取长度,单位字节 /// public static string ReadBigFileStr(string filePath, int Length) { byte[] buffer = ReadBigFile(filePath, Length); return Encoding.Default.GetString(buffer); } #endregion #region 从文件的绝对路径中获取文件名( 包含扩展名 ) /// /// 从文件的绝对路径中获取文件名( 包含扩展名 ) /// /// 文件的绝对路径 public static string GetFileName(string filePath) { //获取文件的名称 FileInfo fi = new FileInfo(filePath); return fi.Name; } /// /// 使用IO从文件的绝对路径中获取文件名( 包含扩展名 ) /// /// 文件的绝对路径 public static string GetIOFileName(string filePath) { return Path.GetFileName(filePath); } #endregion #region 从文件的绝对路径中获取文件名( 不包含扩展名 ) /// /// 从文件的绝对路径中获取文件名( 不包含扩展名 ) /// /// 文件的绝对路径 public static string GetFileNameNoExtension(string filePath) { //获取文件的名称 FileInfo fi = new FileInfo(filePath); return fi.Name.Split('.')[0]; } /// /// 使用IO从文件的绝对路径中获取文件名( 不包含扩展名 ) /// /// 文件的绝对路径 public static string GetIOFileNameNoExtension(string filePath) { return System.IO.Path.GetFileNameWithoutExtension(filePath); } #endregion #region 从文件的绝对路径中获取扩展名 /// /// 从文件的绝对路径中获取扩展名 /// /// 文件的绝对路径 public static string GetExtension(string filePath) { //获取文件的名称 FileInfo fi = new FileInfo(filePath); return fi.Extension; } /// /// 使用IO从文件的绝对路径中获取扩展名 /// /// 文件的绝对路径 public static string GetIOExtension(string filePath) { string Extension = System.IO.Path.GetExtension(filePath); return Extension; } #endregion #region 从文件的绝对路径中获取路径名 /// /// 使用IO从文件的绝对路径中获取路径名 /// /// 文件的绝对路径 public static string GetDirectoryName(string filePath) { string DirectoryName = (System.IO.Path.GetDirectoryName(filePath) + @"/").Replace("\\", "/"); return DirectoryName; } #endregion #region 清空指定目录 /// /// 清空指定目录下所有文件及子目录,但该目录依然保存. /// /// 指定目录的绝对路径 public static void ClearDirectory(string directoryPath) { if (IsExistDirectory(directoryPath)) { //删除目录中所有的文件 string[] fileNames = GetFileNames(directoryPath); foreach (string t in fileNames) { DeleteFile(t); } //删除目录中所有的子目录 string[] directoryNames = GetDirectories(directoryPath); foreach (string t in directoryNames) { DeleteDirectory(t); } } } #endregion #region 清空文件内容 /// /// 清空文件内容 /// /// 文件的绝对路径 public static void ClearFile(string filePath) { //删除文件 File.Delete(filePath); //重新创建该文件 CreateFile(filePath); } #endregion #region 删除指定文件 /// /// 删除指定文件 /// /// 文件的绝对路径 public static void DeleteFile(string filePath) { try { if (IsExistFile(filePath)) { File.Delete(filePath); } } catch (Exception) { } } #endregion #region 删除指定目录 /// /// 删除指定目录及其所有子目录 /// /// 指定目录的绝对路径 public static bool DeleteDirectory(string directoryPath) { try { if (IsExistDirectory(directoryPath)) { Directory.Delete(directoryPath, true); } return true; } catch (Exception) { //目录中有文件占用 return false; } } #endregion #region 获取指定目录大小 /// /// 获取目录大小 /// /// 目录地址 /// 单位:MB public static double PathSize(string directoryPath) { DirectoryInfo folder = new DirectoryInfo(directoryPath); double DirectorySize = DirSize(folder); for (int i = 0; i < 2; i++) { DirectorySize /= 1024; } return DirectorySize; } /// /// 获取目录大小 /// /// 目录 /// 字节 public static long DirSize(DirectoryInfo d) { long Size = 0; // 所有文件大小. FileInfo[] fis = d.GetFiles(); foreach (FileInfo fi in fis) { Size += fi.Length; } // 遍历出当前目录的所有文件夹. DirectoryInfo[] dis = d.GetDirectories(); foreach (DirectoryInfo di in dis) { Size += DirSize(di); //这就用到递归了,调用父方法,注意,这里并不是直接返回值,而是调用父返回来的 } return (Size); } #endregion #region 移动目录 /// /// 移动目录并重命名 /// /// 操作目录绝对路径 /// 目标目录绝对路径 /// 返回错误消息,成功则为空 /// public static bool MoveDirectory(string directoryPath, string newDirectoryPath, out string Message) { Message = ""; try { if (!IsExistDirectory(directoryPath))//判断目录是否存在 { Message = "操作目录不存在!"; return false; } if (IsExistDirectory(newDirectoryPath)) { Message = "目标目录已存在!"; return false; } Directory.Move(directoryPath, newDirectoryPath); return true; } catch (Exception ex) { Message = ex.Message; return false; } } #endregion #region 操作配置文件 #region 从配置文件获取Value /// /// 从配置文件获取Value /// /// 配置文件中key字符串 /// public static string GetConfigValue(string key) { try { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); //获取AppSettings的节点 AppSettingsSection appsection = (AppSettingsSection)config.GetSection("appSettings"); return appsection.Settings[key].Value; } catch { return ""; } } #endregion #region 设置配置文件 /// /// 设置配置文件 /// /// 配置文件中key字符串 /// 配置文件中value字符串 /// public static bool SetConfigValue(string key, string value) { try { //打开配置文件 Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); //获取AppSettings的节点 AppSettingsSection appsection = (AppSettingsSection)config.GetSection("appSettings"); appsection.Settings[key].Value = value; config.Save(); return true; } catch { return false; } } #endregion #endregion #region 获取媒体文件的播放时长 #endregion #region 检测是否安装了某个程序 /// /// 确认电脑上是否安装有某个程序 /// /// 程序安装后的名称 /// true: 有安裝, false:沒有安裝 public static bool CheckSoftWartInstallState(string softWareName) { Microsoft.Win32.RegistryKey uninstallNode = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", Microsoft.Win32.RegistryKeyPermissionCheck.ReadWriteSubTree, System.Security.AccessControl.RegistryRights.ReadKey); foreach (string subKeyName in uninstallNode.GetSubKeyNames()) { Microsoft.Win32.RegistryKey subKey = uninstallNode.OpenSubKey(subKeyName); object displayName = subKey.GetValue("DisplayName"); if (displayName != null) { if (displayName.ToString().Contains(softWareName)) { return true; // MessageWindow.Show(displayName.ToString()); } } } return false; } #endregion } }