大家好,我是阿赵。
这里来分享一下一些方法封装的问题。C#本身是带有IO操作的,只要using System.IO,然后就可以调用File或者Directory的对应API来对文件或者文件夹进行操作。但我的个人习惯是,还会在这上面封装一层自己的方法,方便自己使用。
举个简单的例子,如果需要保存一个文件,使用IO提供的API正常的操作是:
1.获得保存的文本
2.指定编码,
3.获取保存的路径,
4.判断保存的路径的文件夹是否已经存在
5.如果文件夹不存在,就先创建文件夹
6.保存文件到路径
这个过程是没有问题,但假如每一次保存的时候,都要写代码去做这几个步骤,会显得很繁琐。所以我封装一个方法,就包含了这些过程,然后每次保存只需要调用一个函数,把路径、内容、编码传入,就保存了。这样就显得很方便。
下面分享2个文件处理的工具类:
1、FileManager.cs
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace azhao.Tools
{
public class FileManager
{
/// <summary>
/// 获得文件的容量
/// </summary>
/// <param name="path">文件路径</param>
/// <returns>字节长度</returns>
static public long GetFileSize(string path)
{
if(IsFileExists(path)==false)
{
return 0;
}
FileInfo info = new FileInfo(path);
return info.Length;
}
/// <summary>
/// 保存字符串到文件
/// </summary>
/// <param name="path">文件路径</param>
/// <param name="content">字符串内容</param>
/// <param name="needUtf8">是否需要用utf8保存</param>
static public void SaveFile(string path, string content, bool needUtf8 = false)
{
CheckFileSavePath(path);
if (needUtf8)
{
UTF8Encoding code = new UTF8Encoding(false);
File.WriteAllText(path, content, code);
}
else
{
File.WriteAllText(path, content, Encoding.Default);
}
}
/// <summary>
/// 保存到文件,编码为UTF8NoBom
/// </summary>
/// <param name="path">文件路径</param>
/// <param name="content">字符串内容</param>
static public void SaveFileUTF8NoBom(string path, string content)
{
CheckFileSavePath(path);
UTF8Encoding utf8 = new UTF8Encoding(false);
File.WriteAllText(path, content, utf8);
}
/// <summary>
/// 指定编码保存字符串到文件
/// </summary>
/// <param name="path">文件路径</param>
/// <param name="content">字符串内容</param>
/// <param name="code">编码类型</param>
static public void SaveFileByCode(string path, string content, Encoding code)
{
CheckFileSavePath(path);
File.WriteAllText(path, content, code);
}
/// <summary>
/// 保存一行字符串到文件结尾
/// </summary>
/// <param name="path"></param>
/// <param name="content"></param>
static public void SaveLine(string path, string content)
{
CheckFileSavePath(path);
StreamWriter f = new StreamWriter(path, true);
f.WriteLine(content);
f.Close();
}
/// <summary>
/// 写入所有行
/// </summary>
/// <param name="path">文件路径</param>
/// <param name="lines">多行的字符串</param>
static public void SaveAllLines(string path,string[] lines)
{
CheckFileSavePath(path);
File.WriteAllLines(path, lines);
}
/// <summary>
/// 保存bytes
/// </summary>
/// <param name="path">文件路径</param>
/// <param name="bytes"></param>
static public void SaveBytes(string path, byte[] bytes)
{
CheckFileSavePath(path);
File.WriteAllBytes(path, bytes);
}
/// <summary>
/// 删除文件夹
/// </summary>
/// <param name="path">文件夹路径</param>
static public void DelFolder(string path)
{
if(!IsDirectoryExists(path))
{
return;
}
Directory.Delete(path,true);
}
/// <summary>
/// 删除文件夹的另外一种写法
/// </summary>
/// <param name="target_dir"></param>
static public void DelDir(string target_dir)
{
string[] files = Directory.GetFiles(target_dir);
string[] dirs = Directory.GetDirectories(target_dir);
foreach (string file in files)
{
File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);
}
foreach (string dir in dirs)
{
DelDir(dir);
}
Directory.Delete(target_dir, false);
}
/// <summary>
/// 删除文件
/// </summary>
/// <param name="path">需要删除的文件路径</param>
static public void DelFile(string path)
{
if(!IsFileExists(path))
{
return;
}
File.Delete(path);
}
/// <summary>
/// 获取所有行
/// </summary>
/// <param name="path">文件路径</param>
/// <returns></returns>
static public string[] ReadAllLines(string path)
{
if (!File.Exists(path))
{
return null;
}
return File.ReadAllLines(path);
}
/// <summary>
/// 读取文件的字符串
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
static public string ReadFileText(string path,bool isUTF8 = false)
{
if (!File.Exists(path))
{
return "";
}
string str = "";
if(isUTF8)
{
str = File.ReadAllText(path, Encoding.UTF8);
}
else
{
str = File.ReadAllText(path, Encoding.Default);
}
return str;
}
/// <summary>
/// 指定编码读取文件字符串
/// </summary>
/// <param name="path">文件路径</param>
/// <param name="encode">编码</param>
/// <returns></returns>
static public string ReadFileTextByEncode(string path, Encoding encode)
{
if (!File.Exists(path))
{
return "";
}
string str = File.ReadAllText(path, encode);
return str;
}
/// <summary>
/// 读取bytes
/// </summary>
/// <param name="path">文件路径</param>
/// <returns></returns>
static public byte[] ReadFileBytes(string path)
{
if (!File.Exists(path))
{
return null;
}
byte[] str = File.ReadAllBytes(path);
return str;
}
/// <summary>
/// 检查某文件夹路径是否存在,如不存在,创建
/// </summary>
/// <param name="path"></param>
static public void CheckDirection(string path)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
/// <summary>
/// 单纯检查某个文件夹路径是否存在
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
static public bool IsDirectoryExists(string path)
{
if (Directory.Exists(path))
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 检查某个文件是否存在
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
static public bool IsFileExists(string path)
{
if (File.Exists(path))
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 获取某目录下所有指定类型的文件的路径
/// </summary>
/// <param name="path"></param>
/// <param name="exName"></param>
/// <returns></returns>
static public List<string> GetAllFiles(string path, string exName)
{
if(!IsDirectoryExists(path))
{
return null;
}
bool needCheckExName = true;
exName = exName.ToLower();
if(string.IsNullOrEmpty(exName))
{
needCheckExName = false;
}
List<string> names = new List<string>();
DirectoryInfo root = new DirectoryInfo(path);
FileInfo[] files = root.GetFiles();
string ex;
for (int i = 0; i < files.Length; i++)
{
if(needCheckExName==true)
{
ex = FilePathHelper.GetExName(files[i].FullName);
ex = ex.ToLower();
if (ex != exName)
{
continue;
}
}
names.Add(StringTools.ChangePathFormat(files[i].FullName));
}
DirectoryInfo[] dirs = root.GetDirectories();
if (dirs.Length > 0)
{
for (int i = 0; i < dirs.Length; i++)
{
List<string> subNames = GetAllFiles(dirs[i].FullName, exName);
if (subNames.Count > 0)
{
for (int j = 0; j < subNames.Count; j++)
{
names.Add(StringTools.ChangePathFormat(subNames[j]));
}
}
}
}
return names;
}
/// <summary>
/// 获取某目录下所有除了指定类型外的文件的路径
/// </summary>
/// <param name="path"></param>
/// <param name="exName"></param>
/// <returns></returns>
static public List<string> GetAllFilesExcept(string path, string exName)
{
if (!IsDirectoryExists(path))
{
return null;
}
List<string> names = new List<string>();
DirectoryInfo root = new DirectoryInfo(path);
FileInfo[] files = root.GetFiles();
string ex;
for (int i = 0; i < files.Length; i++)
{
ex = FilePathHelper.GetExName(files[i].FullName);
if (ex == exName)
{
continue;
}
names.Add(StringTools.ChangePathFormat(files[i].FullName));
}
DirectoryInfo[] dirs = root.GetDirectories();
if (dirs.Length > 0)
{
for (int i = 0; i < dirs.Length; i++)
{
List<string> subNames = GetAllFilesExcept(dirs[i].FullName, exName);
if (subNames.Count > 0)
{
for (int j = 0; j < subNames.Count; j++)
{
names.Add(StringTools.ChangePathFormat(subNames[j]));
}
}
}
}
return names;
}
/// <summary>
/// 获取某目录下所有除了指定类型外的文件的路径
/// </summary>
/// <param name="path"></param>
/// <param name="exName"></param>
/// <returns></returns>
static public List<string> GetAllFilesIncludeList(string path, List<string> exName)
{
if (!IsDirectoryExists(path))
{
return null;
}
List<string> names = new List<string>();
DirectoryInfo root = new DirectoryInfo(path);
FileInfo[] files = root.GetFiles();
for (int i = 0; i < exName.Count; i++)
{
exName[i] = exName[i].ToLower();
}
string ex;
for (int i = 0; i < files.Length; i++)
{
ex = FilePathHelper.GetExName(files[i].FullName);
ex = ex.ToLower();
if (exName.IndexOf(ex) < 0)
{
continue;
}
names.Add(StringTools.ChangePathFormat(files[i].FullName));
}
DirectoryInfo[] dirs = root.GetDirectories();
if (dirs.Length > 0)
{
for (int i = 0; i < dirs.Length; i++)
{
List<string> subNames = GetAllFilesIncludeList(dirs[i].FullName, exName);
if (subNames.Count > 0)
{
for (int j = 0; j < subNames.Count; j++)
{
names.Add(StringTools.ChangePathFormat(subNames[j]));
}
}
}
}
return names;
}
/// <summary>
/// 获取某目录下所有除了指定类型外的文件的路径
/// </summary>
/// <param name="path"></param>
/// <param name="exName"></param>
/// <returns></returns>
static public List<string> GetAllFilesExceptList(string path,List<string> exName)
{
if (!IsDirectoryExists(path))
{
return null;
}
List<string> names = new List<string>();
DirectoryInfo root = new DirectoryInfo(path);
FileInfo[] files = root.GetFiles();
for(int i = 0;i<exName.Count;i++)
{
exName[i] = exName[i].ToLower();
}
string ex;
for (int i = 0; i < files.Length; i++)
{
ex = FilePathHelper.GetExName(files[i].FullName);
ex = ex.ToLower();
if (exName.IndexOf(ex)>=0)
{
continue;
}
names.Add(StringTools.ChangePathFormat(files[i].FullName));
}
DirectoryInfo[] dirs = root.GetDirectories();
if (dirs.Length > 0)
{
for (int i = 0; i < dirs.Length; i++)
{
List<string> subNames = GetAllFilesExceptList(dirs[i].FullName, exName);
if (subNames.Count > 0)
{
for (int j = 0; j < subNames.Count; j++)
{
names.Add(StringTools.ChangePathFormat(subNames[j]));
}
}
}
}
return names;
}
/// <summary>
/// 获取指定路径下第一层的子文件夹路径
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
static public List<string> GetSubFolders(string path)
{
if(!IsDirectoryExists(path))
{
return null;
}
DirectoryInfo root = new DirectoryInfo(path);
DirectoryInfo[] dirs = root.GetDirectories();
List<string> folders = new List<string>();
if (dirs.Length > 0)
{
for (int i = 0; i < dirs.Length; i++)
{
folders.Add(StringTools.ChangePathFormat(dirs[i].FullName));
}
}
return folders;
}
/// <summary>
/// 获取指定路径下一层的指定格式的文件的路径
/// </summary>
/// <param name="path"></param>
/// <param name="exName"></param>
/// <returns></returns>
static public List<string> GetSubFiles(string path, string exName)
{
List<string> names = new List<string>();
if(IsDirectoryExists(path)==false)
{
return names;
}
bool needCheck = true;
if(string.IsNullOrEmpty(exName)==true)
{
needCheck = false;
}
DirectoryInfo root = new DirectoryInfo(path);
FileInfo[] files = root.GetFiles();
string ex;
for (int i = 0; i < files.Length; i++)
{
ex = FilePathHelper.GetExName(files[i].FullName);
if (needCheck == true && ex != exName)
{
continue;
}
names.Add(StringTools.ChangePathFormat(files[i].FullName));
}
return names;
}
/// <summary>
/// 获取指定路径下一层的除指定格式以外的文件的路径
/// </summary>
/// <param name="path"></param>
/// <param name="exName"></param>
/// <returns></returns>
static public List<string> GetSubFilesExcept(string path, string exName)
{
List<string> names = new List<string>();
if (IsDirectoryExists(path) == false)
{
return names;
}
DirectoryInfo root = new DirectoryInfo(path);
FileInfo[] files = root.GetFiles();
string ex;
for (int i = 0; i < files.Length; i++)
{
ex = FilePathHelper.GetExName(files[i].FullName);
if (ex == exName)
{
continue;
}
names.Add(StringTools.ChangePathFormat(files[i].FullName));
}
return names;
}
/// <summary>
/// 获取指定路径下一层的包含列表里扩展名的文件
/// </summary>
/// <param name="path"></param>
/// <param name="exName"></param>
/// <returns></returns>
static public List<string> GetSubFilesIncude(string path, List<string>includeList)
{
List<string> names = new List<string>();
if (IsDirectoryExists(path) == false)
{
return names;
}
DirectoryInfo root = new DirectoryInfo(path);
FileInfo[] files = root.GetFiles();
string ex;
for (int i = 0; i < files.Length; i++)
{
ex = FilePathHelper.GetExName(files[i].FullName);
if (includeList.IndexOf(ex)>=0)
{
names.Add(StringTools.ChangePathFormat(files[i].FullName));
}
}
return names;
}
/// <summary>
/// 检查需要保存的文件所在的文件夹是否存在。若不存在就创建
/// </summary>
/// <param name="path"></param>
static public void CheckFileSavePath(string path)
{
string realPath = path;
int ind = path.LastIndexOf("/");
if (ind >= 0)
{
realPath = path.Substring(0, ind);
}
else
{
ind = path.LastIndexOf("\\");
if (ind >= 0)
{
realPath = path.Substring(0, ind);
}
}
CheckDirection(realPath);
}
static public void CopyFile(string path,string tarPath)
{
if(!IsFileExists(path))
{
return;
}
CheckFileSavePath(tarPath);
File.Copy(path, tarPath, true);
}
/// <summary>
/// 剪切文件夹到指定路径
/// </summary>
/// <param name="orgPath"></param>
/// <param name="tarPath"></param>
static public void MoveFolder(string orgPath,string tarPath)
{
DirectoryInfo folder = new DirectoryInfo(orgPath);
if (folder.Exists)
{
CheckDirection(tarPath);
Directory.Delete(tarPath);
folder.MoveTo(tarPath);
}
}
/// <summary>
/// 复制文件夹
/// </summary>
/// <param name="orgPath"></param>
/// <param name="tarPath"></param>
static public void CopyFolder(string orgPath, string tarPath)
{
DirectoryInfo folder = new DirectoryInfo(orgPath);
if (folder.Exists)
{
CheckDirection(tarPath);
List<string> subPaths = FileManager.GetAllFiles(orgPath,"");
for(int i = 0;i<subPaths.Count;i++)
{
string tarSubPath = subPaths[i].Replace(orgPath, "");
tarSubPath = tarPath + tarSubPath;
CopyFile(subPaths[i], tarSubPath);
}
}
}
/// <summary>
/// 把原文件夹里面指定扩展名的文件复制到目标文件夹
/// </summary>
/// <param name="orgPath">源文件夹</param>
/// <param name="tarPath">目标文件夹</param>
/// <param name="exName">扩展名</param>
static public void CopyFolderByExName(string orgPath, string tarPath, string exName)
{
if (exName == null)
{
exName = "";
}
DirectoryInfo folder = new DirectoryInfo(orgPath);
if (folder.Exists)
{
CheckDirection(tarPath);
List<string> subPaths = FileManager.GetAllFiles(orgPath, exName);
for (int i = 0; i < subPaths.Count; i++)
{
string tarSubPath = subPaths[i].Replace(orgPath, "");
tarSubPath = tarPath + tarSubPath;
CopyFile(subPaths[i], tarSubPath);
}
}
}
/// <summary>
/// 把原文件夹里面除了指定扩展名以外的文件复制到目标文件夹
/// </summary>
/// <param name="orgPath">原文件夹</param>
/// <param name="tarPath">目标文件夹</param>
/// <param name="exName">排除的扩展名</param>
static public void CopyFolderByExceptExName(string orgPath, string tarPath, string exName)
{
if (exName == null)
{
exName = "";
}
DirectoryInfo folder = new DirectoryInfo(orgPath);
if (folder.Exists)
{
CheckDirection(tarPath);
List<string> subPaths = FileManager.GetAllFilesExcept(orgPath, exName);
for (int i = 0; i < subPaths.Count; i++)
{
string tarSubPath = subPaths[i].Replace(orgPath, "");
tarSubPath = tarPath + tarSubPath;
CopyFile(subPaths[i], tarSubPath);
}
}
}
/// <summary>
/// 移动文件夹
/// </summary>
/// <param name="orgPath"></param>
/// <param name="tarPath"></param>
static public void MoveFile(string orgPath, string tarPath)
{
if (File.Exists(orgPath) == false)
{
return;
}
File.Move(orgPath, tarPath);
}
}
}
2、FilePathHelper
namespace azhao.Tools
{
/// <summary>
/// 针对文件路径的处理工具
/// </summary>
public class FilePathHelper
{
/// <summary>
/// 获得文件名
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
static public string GetFileName(string str)
{
string rexStr = @"(?<=\\)[^\\]+$|(?<=/)[^/]+$";
return StringTools.GetFirstMatch(str, rexStr);
}
static public string GetFileNameRemoveEx(string str)
{
str = GetFileName(str);
str = RemoveExName(str);
return str;
}
/// <summary>
/// 获得扩展名
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
static public string GetExName(string str)
{
string rexStr = @"(?<=\\[^\\]+.)[^\\.]+$|(?<=/[^/]+.)[^/.]+$";
return StringTools.GetFirstMatch(str, rexStr);
}
/// <summary>
/// 去除扩展名
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
static public string RemoveExName(string str)
{
string returnStr = str;
string rexStr = @"[^\.]+(?=\.)";
string xStr = StringTools.GetFirstMatch(str, rexStr);
if (!string.IsNullOrEmpty(xStr))
{
returnStr = xStr;
}
return returnStr;
}
}
}