前言

文件操作帮助类,包含下表中的方法:

方法名方法解释
GetFileNames获取指定目录中所有文件列表
GetDirectories获取指定目录中的子目录列表
GetDirectoryCreateTime获取文件夹的创建时间
GetFileCreateTime获取文件的创建时间
GetFileSize获取一个文件的长度,单位为Byte
GetFileSizeByKB获取一个文件的长度,单位为KB
GetFileSizeByMB获取一个文件的长度,单位为MB
GetDirectoryLength获取一个文件夹的长度,单位为Byte
FileRename文件重命名
DirRename文件夹重命名
Copy将源文件的内容复制到目标文件中(文件复制)
CopyDirectory将文件夹复制到指定目录(文件夹复制)
FileMove将文件移动到指定目录(文件剪切)
DirMove将文件夹移动到指定目录 (文件夹剪切)
DeleteFile删除指定文件
DeleteDirectory删除指定文件夹
方法过多,就不一一赘述,需要的同学自行查看

代码示例

using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Text;using System.Threading.Tasks;namespace VW.API.Common.Utils{/// /// FileHelper 的摘要说明:文件(夹)帮助类/// public static class FileHelper{#region 获取指定目录中的文件列表/// /// 获取指定目录中所有文件列表/// /// 指定目录的绝对路径public static string[] GetFileNames(string directoryPath){try{//如果目录不存在,则抛出异常if (!IsExistDirectory(directoryPath)){Directory.CreateDirectory(directoryPath);}//获取文件列表return Directory.GetFiles(directoryPath);}catch (Exception){return new string[] { };}}/// /// 获取指定目录及子目录中所有文件列表/// /// 指定目录的绝对路径/// 模式字符串,"*"代表0或N个字符,"?"代表1个字符。/// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。/// 是否搜索子目录public static string[] GetFileNames(string directoryPath, string searchPattern, bool isSearchChild){//如果目录不存在,则抛出异常if (!IsExistDirectory(directoryPath)){return new string[] { };}try{return Directory.GetFiles(directoryPath, searchPattern, isSearchChild ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);}catch{return new string[] { };}}#endregion#region 获取指定目录中的子目录列表/// /// 获取指定目录中所有子目录列表,若要搜索嵌套的子目录列表,请使用重载方法./// /// 指定目录的绝对路径public static string[] GetDirectories(string directoryPath){try{if (!IsExistDirectory(directoryPath))return new string[] { };elsereturn Directory.GetDirectories(directoryPath);}catch (Exception) { throw; }}/// /// 获取指定目录及子目录中所有子目录列表/// /// 指定目录的绝对路径/// 模式字符串,"*"代表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{throw null;}}#endregion#region 从目录的绝对路径中获取文件夹名/// /// 从目录的绝对路径中获取文件夹名/// /// 文件夹的绝对路径public static string GetDirectoryName(string directoryPath){//获取文件的名称DirectoryInfo directoryInfo = new DirectoryInfo(directoryPath);return directoryInfo.Name;}#endregion#region 获取文件夹的创建时间/// /// 获取文件夹的创建时间/// /// 文件夹的绝对路径public static DateTime GetDirectoryCreateTime(string directoryPath){//获取文件夹的创建时间DirectoryInfo directoryInfo = new DirectoryInfo(directoryPath);return directoryInfo.CreationTime;}#endregion#region 获取文件的创建时间/// /// 获取文件的创建时间/// /// 文件的绝对路径public static DateTime GetFileCreateTime(string filePath){//获取文件的创建时间FileInfo fileInfo = new FileInfo(filePath);return fileInfo.CreationTime;}#endregion#region 获取一个文件的长度/// /// 获取一个文件的长度,单位为Byte/// /// 文件的绝对路径public static long GetFileSize(string filePath){try{//创建一个文件对象FileInfo fi = new FileInfo(filePath);//获取文件的大小return (long)fi.Length;}catch (Exception) { throw; }}/// /// 获取一个文件的长度,单位为KB/// /// 文件的路径public static double GetFileSizeByKB(string filePath){try{//创建一个文件对象FileInfo fi = new FileInfo(filePath);long size = fi.Length / 1024;//获取文件的大小return double.Parse(size.ToString());}catch (Exception) { throw; }}/// /// 获取一个文件的长度,单位为MB/// /// 文件的路径public static double GetFileSizeByMB(string filePath){try{//创建一个文件对象FileInfo fi = new FileInfo(filePath);long size = fi.Length / 1024 / 1024;//获取文件的大小return double.Parse(size.ToString());}catch (Exception) { throw; }}#endregion#region 获取一个文件夹的长度/// /// 获取一个文件夹的长度/// /// 路径/// public static long GetDirectoryLength(string dirPath){try{long len = 0;//定义一个DirectoryInfo对象DirectoryInfo di = new DirectoryInfo(dirPath);//通过GetFiles方法,获取di目录中的所有文件的大小foreach (FileInfo fi in di.GetFiles()){len += fi.Length;}//获取di中所有的文件夹,并存到一个新的对象数组中,以进行递归DirectoryInfo[] dis = di.GetDirectories();if (dis.Length > 0){for (int i = 0; i < dis.Length; i++){len += GetDirectoryLength(dis[i].FullName);}}return len;}catch (Exception) { throw; }}#endregion#region 文件重命名/// /// 文件重命名/// /// 源文件的绝对路径/// 目标文件的绝对路径public static void FileRename(string sourceFilePath, string destFilePath){try{if (IsExistFile(sourceFilePath)){FileInfo fi = new FileInfo(sourceFilePath);fi.MoveTo(destFilePath, true);}}catch (Exception) { throw; }}#endregion#region 文件夹重命名/// /// 文件夹重命名/// /// 源文件夹的绝对路径/// 目标文件夹的绝对路径public static void DirRename(string sourceDirPath, string destDirPath){try{DirectoryInfo di = new DirectoryInfo(sourceDirPath);di.MoveTo(destDirPath);}catch (Exception) { throw; }}#endregion#region 将现有文件的内容复制到新文件中/// /// 获取当天日期/// /// private static string GetDate(){DateTime dt = DateTime.Now;// 年string year = string.Format("{0:D4}", dt.Year);// 月string month = string.Format("{0:D2}", dt.Month);// 日string day = string.Format("{0:D2}", dt.Day);// 秒string millisecond = string.Format("{0:D4}", dt.Millisecond);// 年月日秒(201705311234)return year + month + day + millisecond;}/// /// 将源文件的内容复制到目标文件中/// /// 源文件的绝对路径/// 目标文件的绝对路径/// 是否覆盖 public static void Copy(string sourceFilePath, string destFilePath, bool overwrite){try{string destDirPath = Path.GetDirectoryName(destFilePath);if (!Directory.Exists(destDirPath))Directory.CreateDirectory(destDirPath);if (overwrite){File.Copy(sourceFilePath, destFilePath, overwrite);}else{// 如果源文件和目标文件重名,则对目标文件加时间标签if (sourceFilePath == destFilePath){FileInfo fiDest = new FileInfo(destFilePath);string fileName = fiDest.Name.Replace(fiDest.Extension, "");string newFileName = fileName + "_" + GetDate();destFilePath = destFilePath.Replace(fileName, newFileName);}File.Copy(sourceFilePath, destFilePath);}}catch (Exception) { throw; }}#endregion#region 将文件移动到指定目录/// /// 将文件移动到指定目录/// /// 需要移动的源文件的绝对路径/// 移动到的目录的绝对路径public static void FileMove(string sourceFilePath, string descDirectoryPath){try{//获取源文件的名称string sourceFileName = GetFileName(sourceFilePath);if (!IsExistDirectory(descDirectoryPath)){CreateDirectory(descDirectoryPath);}//如果目标中存在同名文件,则删除if (IsExistFile(Path.Combine(descDirectoryPath, sourceFileName))){DeleteFile(Path.Combine(descDirectoryPath, sourceFileName));}//将文件移动到指定目录File.Move(sourceFilePath, Path.Combine(descDirectoryPath, sourceFileName));}catch (Exception) { throw; }}#endregion#region 将文件夹移动到指定目录/// /// 将文件夹移动到指定目录/// /// 需要移动的源文件夹的绝对路径/// 移动到的目录的绝对路径public static void DirMove(string sourceDirPath, string descDirectoryPath){try{DirectoryInfo di = new DirectoryInfo(sourceDirPath);descDirectoryPath = descDirectoryPath + "/" + di.Name;if (!Directory.Exists(sourceDirPath))return;if (!Directory.Exists(descDirectoryPath))Directory.CreateDirectory(descDirectoryPath);string[] files = Directory.GetFiles(sourceDirPath);foreach (string formFileName in files){string fileName = Path.GetFileName(formFileName);string toFileName = Path.Combine(descDirectoryPath, fileName);File.Copy(formFileName, toFileName, true);}string[] fromDirs = Directory.GetDirectories(sourceDirPath);foreach (string fromDirName in fromDirs){string dirName = Path.GetFileName(fromDirName);string toDirName = Path.Combine(descDirectoryPath, dirName);DirMove(fromDirName, toDirName);}Directory.Delete(sourceDirPath, true);}catch (Exception) { throw; }}#endregion#region 将文件夹复制到指定目录public static void CopyDirectory(string srcPath, string destPath){try{DirectoryInfo dir = new DirectoryInfo(srcPath);FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();foreach (FileSystemInfo i in fileinfo){if (i is DirectoryInfo){if (!Directory.Exists(destPath + "\\" + i.Name))Directory.CreateDirectory(destPath + "\\" + i.Name);CopyDirectory(i.FullName, destPath + "\\" + i.Name);}elseFile.Copy(i.FullName, destPath + "\\" + i.Name, true);}}catch (Exception) { throw; }}#endregion#region 删除指定文件/// /// 删除指定文件/// /// 文件的绝对路径public static void DeleteFile(string filePath){try{if (IsExistFile(filePath)){File.Delete(filePath);}}catch (Exception) { throw; }}#endregion#region 删除指定目录/// /// 删除指定目录及其所有子目录/// /// 指定目录的绝对路径public static void DeleteDirectory(string directoryPath){try{if (IsExistDirectory(directoryPath)){Directory.Delete(directoryPath, true);}}catch (Exception) { throw; }}#endregion#region 创建一个目录/// /// 创建一个目录/// /// 目录的绝对路径public static void CreateDirectory(string directoryPath){try{//如果目录不存在则创建该目录if (!IsExistDirectory(directoryPath)){Directory.CreateDirectory(directoryPath);}}catch (Exception) { throw; }}#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 bool CreateFile(string filePath){try{//如果文件不存在则创建该文件if (!IsExistFile(filePath)){//创建一个FileInfo对象FileInfo file = new FileInfo(filePath);//文件夹不存在,创建文件夹if (!IsExistDirectory(file.Directory.FullName)){CreateDirectory(file.Directory.FullName);}//创建文件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);//文件夹不存在,创建文件夹if (!IsExistDirectory(file.Directory.FullName)){CreateDirectory(file.Directory.FullName);}//创建文件FileStream fs = file.Create();//写入二进制流fs.Write(buffer, 0, buffer.Length);//关闭文件流fs.Close();}}catch{return false;}return true;}/// /// 创建一个文件,并将数据流写入文件。/// /// 文件的绝对路径/// 数据流public static bool CreateFile(string filePath, Stream stream){try{//如果文件不存在则创建该文件if (!IsExistFile(filePath)){//创建一个FileInfo对象FileInfo file = new FileInfo(filePath);//文件夹不存在,创建文件夹if (!IsExistDirectory(file.Directory.FullName)){CreateDirectory(file.Directory.FullName);}//创建文件FileStream fs = file.Create();byte[] buffer = new Byte[stream.Length];stream.Read(buffer, 0, buffer.Length);stream.Seek(0, SeekOrigin.Begin);//写入二进制流fs.Write(buffer, 0, buffer.Length);//关闭文件流fs.Close();}}catch (Exception){return false;}return true;}/// /// 创建多个文件,并将数据流写入文件。/// /// 根目录/// 文件名-数据流public static List CreateFile(string rootDir, Dictionary files, bool isRename = false){try{List list = new List();foreach (KeyValuePair keyValue in files){if (isRename)//是否以时间戳命名重命名{string fileName = $"{CommonHelper.UnixTimeUidByDataTime(DateTime.Now)}{GetExtension(keyValue.Key)}";string filePath = Path.Combine(rootDir, fileName);if (!CreateFile(filePath, keyValue.Value)){throw new FileNotFoundException($"文件({keyValue.Key})生成失败。");}list.Add(fileName);}else{string fileName = keyValue.Key;string filePath = Path.Combine(rootDir, keyValue.Key);if (IsExistFile(filePath))fileName = $"({DateTime.Now.ObjToDateYMDHMS()}){keyValue.Key}";filePath = Path.Combine(rootDir, fileName);if (!CreateFile(filePath, keyValue.Value)){throw new FileNotFoundException($"文件({keyValue.Key})生成失败。");}list.Add(fileName);}}return list;}catch (Exception){throw;}}#endregion#region 获取文本文件的行数/// /// 获取文本文件的行数/// /// 文件的绝对路径public static int GetLineCount(string filePath){//将文本文件的各行读到一个字符串数组中string[] rows = File.ReadAllLines(filePath);//返回行数return rows.Length;}#endregion#region 获取文本文件的各行数据/// /// 获取文本文件的各行数据/// /// 文件的绝对路径public static string[] GetAllLines(string filePath){//将文本文件的各行读到一个字符串数组中string[] lines = File.ReadAllLines(filePath);//返回行数return lines;}#endregion#region 向文本文件写入内容/// /// 向文本文件中写入内容/// /// 文件的绝对路径/// 写入的内容public static void WriteText(string filePath, string content, Encoding encoding){//向文件写入内容File.WriteAllText(filePath, content, encoding);}/// /// 向文本文件中写入内容/// /// 文件的绝对路径/// 写入的内容public static void WriteText(string filePath, string content){//向文件写入内容File.WriteAllText(filePath, content, Encoding.UTF8);}#endregion#region 向文本文件的尾部追加内容/// /// 向文本文件的尾部追加内容/// /// 文件的绝对路径/// 写入的内容public static void AppendText(string filePath, string content){File.AppendAllText(filePath, content);}#endregion#region 将流读取到缓冲区中/// /// 将流读取到缓冲区中/// /// 原始流public static byte[] StreamToBytes(Stream stream, int length){try{length = stream.Length > length ? length : (int)stream.Length;//创建缓冲区byte[] buffer = new byte[length];//读取流stream.Read(buffer, 0, length);//返回流return buffer;}catch (Exception) { throw; }finally{stream.Position = 0;//关闭流//stream.Close();}}#endregion#region 将文件读取到缓冲区中/// /// 将文件读取到缓冲区中/// /// 文件的绝对路径public static byte[] FileToBytes(string filePath){//获取文件的大小 int fileSize = (int)GetFileSize(filePath);//创建一个临时缓冲区byte[] buffer = new byte[fileSize];//创建一个文件流FileInfo fi = new FileInfo(filePath);FileStream fs = fi.Open(FileMode.Open);try{//将文件流读入缓冲区fs.Read(buffer, 0, fileSize);return buffer;}catch{return null;}finally{//关闭文件流fs.Close();}}#endregion#region 向文本文件的写入多行/// /// 向文本文件的写入多行/// /// 文件的绝对路径/// 写入的内容public static void WriteAllLines(string filePath, string[] contents){File.WriteAllLines(filePath, contents);}#endregion#region 将文件读取到缓冲区中/// /// 将文件读取到缓冲区中/// /// 文件的绝对路径public static Stream FileToStream(string filePath){//获取文件的大小 int fileSize = (int)GetFileSize(filePath);//创建一个临时缓冲区byte[] buffer = new byte[fileSize];Stream stream = null;//创建一个文件流FileInfo fi = new FileInfo(filePath);FileStream fs = fi.Open(FileMode.Open);try{//将文件流读入缓冲区fs.Read(buffer, 0, fileSize);stream = new MemoryStream(buffer);return stream;}catch{return null;}finally{//关闭文件流fs.Close();}}#endregion#region 将文件读取到字符串中/// /// 将文件读取到字符串中/// /// 文件的绝对路径public static string FileToString(string filePath){return FileToString(filePath, Encoding.Default);}/// /// 将文件读取到字符串中/// /// 文件的绝对路径/// 字符编码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 async Task FileToStringAsync(string filePath, Encoding encoding){//创建流读取器StreamReader reader = new StreamReader(filePath, encoding);try{//读取流return await reader.ReadToEndAsync();}catch{return string.Empty;}finally{//关闭流读取器reader.Close();}}#endregion#region 从文件的绝对路径中获取文件名( 包含扩展名 )/// /// 从文件的绝对路径中获取文件名( 包含扩展名 )/// /// 文件的绝对路径public static string GetFileName(string filePath){//获取文件的名称FileInfo fi = new FileInfo(filePath);return fi.Name;}#endregion#region 从文件的绝对路径中获取文件名( 不包含扩展名 )/// /// 从文件的绝对路径中获取文件名( 不包含扩展名 )/// /// 文件的绝对路径public static string GetFileNameNoExtension(string filePath){//获取文件的名称FileInfo fi = new FileInfo(filePath);string extension = fi.Extension;return fi.Name.Replace(extension, "");}#endregion#region 从文件的绝对路径中获取扩展名/// /// 从文件的绝对路径中获取扩展名/// /// 文件的绝对路径public static string GetExtension(string filePath){//获取文件的名称FileInfo fi = new FileInfo(filePath);return fi.Extension;}#endregion#region 从文件的绝对路径中获取目录路径/// /// 从文件的绝对路径中获取目录路径/// /// 文件的绝对路径public static string GetFileDirPath(string filePath){//获取文件的名称FileInfo fi = new FileInfo(filePath);return fi.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 long GetDiskTotalSize(string diskName){long totalSize = new long();diskName += ":\\";DriveInfo[] drives = DriveInfo.GetDrives();foreach (DriveInfo drive in drives){if (drive.Name == diskName){totalSize = drive.TotalSize / (1024 * 1024 * 1024);break;}}return totalSize;}#endregion#region 获取磁盘剩余空间/// /// 获取磁盘剩余空间/// /// /// public static long GetDiskFreeSize(string diskName){long freeSize = new long();diskName += ":\\";DriveInfo[] drives = DriveInfo.GetDrives();foreach (DriveInfo drive in drives){if (drive.Name == diskName){freeSize = drive.TotalFreeSpace / (1024 * 1024 * 1024);break;}}return freeSize;}#endregion#region 获取磁盘已用空间/// /// 获取磁盘已用空间/// /// /// public static long GetDiskUsedSize(string diskName){long usedSize = new long();diskName += ":\\";DriveInfo[] drives = DriveInfo.GetDrives();foreach (DriveInfo drive in drives){if (drive.Name == diskName){usedSize = drive.TotalSize / (1024 * 1024 * 1024) - drive.TotalFreeSpace / (1024 * 1024 * 1024);break;}}return usedSize;}#endregion#region 判断目标是文件夹还是目录/// /// 判断目标是文件夹还是目录(目录包括磁盘)/// /// 路径/// 返回true为一个文件夹,返回false为一个文件public static bool IsDir(string filePath){FileInfo fi = new FileInfo(filePath);if ((fi.Attributes & FileAttributes.Directory) != 0)return true;elsereturn false;}#endregion#region 动态计算文件大小static public string FormatBytes(long bytes){string[] magnitudes = new string[] { "GB", "MB", "KB", "Bytes" };long max = (long)Math.Pow(1024, magnitudes.Length);return string.Format("{1:##.##} {0}",magnitudes.FirstOrDefault(magnitude => bytes > (max /= 1024)) ?? "0 Bytes",(decimal)bytes / (decimal)max).Trim();}#endregion}}