using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms; namespace DocDecrypt.Common
{
public class FileHelper
{
private static readonly log4net.ILog _logger = log4net.LogManager.GetLogger("FileHelper"); private static void PrintExcetpion(string errors, Exception ex)
{
_logger.ErrorFormat(errors + " {0} \r\n {1}", ex.Message, ex.StackTrace);
} public static string GetTempFileName(string fileName)
{
return Path.Combine(Path.GetTempPath(), string.IsNullOrEmpty(fileName) ? "~temp.tmp" : fileName);
} ///////////////////////////////////
// 文件基本操作
public static void ClearOrCreatePath(string dstPath)
{
if (Directory.Exists(dstPath))
ClearPath(dstPath);
else
CreateDirectoy(dstPath);
} public static void ClearPath(string dstPath)
{
try
{
if (!new System.IO.DirectoryInfo(dstPath).Exists)
return; foreach (string d in System.IO.Directory.GetFileSystemEntries(dstPath))
{
if (System.IO.File.Exists(d))
{
System.IO.FileInfo fi = new System.IO.FileInfo(d);
DeleteFile(fi); // 直接删除其中的文件
}
else
{
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(d);
DeletePath(di.FullName); // 删除子文件夹
}
}
}
catch (Exception ex)
{
PrintExcetpion(string.Format("清除文件夹失败-{0}", dstPath),ex);
}
} /// <summary>
/// 删除目录下的所有文件(只删除文件)
/// </summary>
/// <param name="dstPath"></param>
public static void DeleteFiles(string dstPath)
{
try
{
if (!new System.IO.DirectoryInfo(dstPath).Exists)
return; foreach (string d in System.IO.Directory.GetFiles(dstPath))
{
if (System.IO.File.Exists(d))
{
System.IO.FileInfo fi = new System.IO.FileInfo(d);
DeleteFile(fi); // 直接删除其中的文件
}
}
}
catch (Exception ex)
{
PrintExcetpion(string.Format("删除目录下的所有文件失败-{0}", dstPath), ex);
}
} public static void DeletePath(string dstPath)
{
try
{
if (!Directory.Exists(dstPath))
return; foreach (string d in System.IO.Directory.GetFileSystemEntries(dstPath))
{
if (System.IO.File.Exists(d))
{
System.IO.FileInfo fi = new System.IO.FileInfo(d);
DeleteFile(fi); // 直接删除其中的文件
}
else
DeletePath(d); // 递归删除子文件夹
} System.IO.Directory.Delete(dstPath); // 删除已空文件夹
}
catch (Exception ex)
{
PrintExcetpion(string.Format("删除文件夹失败-{0}", dstPath), ex);
}
} public static void CopyFile(string src, string dst)
{
try
{
if (src.ToLower() == dst.ToLower())
return; if (!File.Exists(src))
return; FileHelper.DeleteFile(dst);
FileHelper.CreateDirectoy(Path.GetDirectoryName(dst)); System.IO.File.Copy(src, dst);
}
catch (Exception ex)
{
PrintExcetpion(string.Format("拷贝文件失败-{0}:{1}", src,dst), ex);
}
} public static bool IsFileExist(string file)
{
return !string.IsNullOrEmpty(file) && File.Exists(file);
} public static bool IsDirExist(string dir)
{
return !string.IsNullOrEmpty(dir) && Directory.Exists(dir);
} public static void MoveFile(string src, string dst)
{
try
{
if (string.Equals(src, dst, StringComparison.CurrentCultureIgnoreCase))
return; if (!File.Exists(src))
return; FileHelper.DeleteFile(dst);
FileHelper.CreateDirectoy(Path.GetDirectoryName(dst)); System.IO.File.Move(src, dst);
}
catch (Exception ex)
{
PrintExcetpion($"移动文件失败-{src}:{dst}", ex);
}
} public static void MovePath(string srcPath, string dstPath)
{
try
{
if (srcPath.ToLower() == dstPath.ToLower())
return; if (!Directory.Exists(srcPath))
return; ClearOrCreatePath(dstPath); System.IO.Directory.Move(srcPath, dstPath);
}
catch (Exception ex)
{
PrintExcetpion(string.Format("拷贝文件失败-{0}:{1}", srcPath, dstPath), ex);
}
} public static string DiskTypeInfo = "Disk"; public static void MovePath_copy_delete(string srcPath, string dstPath)
{
try
{
if (srcPath.ToLower() == dstPath.ToLower())
return; if (!Directory.Exists(srcPath))
return; ClearOrCreatePath(dstPath); MoveDirectory(srcPath, dstPath);
if (DiskTypeInfo == "Disk")
{
DeletePath(srcPath);
} }
catch (Exception ex)
{
PrintExcetpion($"拷贝删除文件失败-{srcPath}:{dstPath}", ex);
}
} /// <summary>
/// 移动整个文件夹
/// </summary>
/// <param name="srcDir"></param>
/// <param name="tgtDir"></param>
public static void MoveDirectory(string srcDir, string tgtDir)
{
if (string.Equals(srcDir, tgtDir, StringComparison.CurrentCultureIgnoreCase))
return; if (!Directory.Exists(srcDir))
return; DirectoryInfo source = new DirectoryInfo(srcDir);
DirectoryInfo target = new DirectoryInfo(tgtDir); if (target.FullName.StartsWith(source.FullName, StringComparison.CurrentCultureIgnoreCase))
{
throw new Exception("父目录不能拷贝到子目录!");
} if (!source.Exists)
{
return;
} if (!target.Exists)
{
target.Create();
} FileInfo[] files = source.GetFiles(); foreach (var file in files)
{
if (DiskTypeInfo == "Disk")
{
File.Move(file.FullName, target.FullName + @"\" + file.Name);
}
else
File.Copy(file.FullName, target.FullName + @"\" + file.Name);
} DirectoryInfo[] dirs = source.GetDirectories(); foreach (var dir in dirs)
{
MoveDirectory(dir.FullName, target.FullName + @"\" + dir.Name);
}
} public static void CopyDirectory(string srcDir, string tgtDir)
{
if (srcDir.ToLower() == tgtDir.ToLower())
return; if (!Directory.Exists(srcDir))
return; DirectoryInfo source = new DirectoryInfo(srcDir);
DirectoryInfo target = new DirectoryInfo(tgtDir); if (target.FullName.StartsWith(source.FullName, StringComparison.CurrentCultureIgnoreCase))
{
throw new Exception("父目录不能拷贝到子目录!");
} if (!source.Exists)
{
return;
} if (!target.Exists)
{
target.Create();
} FileInfo[] files = source.GetFiles(); foreach (var file in files)
{
File.Copy(file.FullName, target.FullName + @"\" + file.Name, true);
} DirectoryInfo[] dirs = source.GetDirectories(); foreach (var dir in dirs)
{
CopyDirectory(dir.FullName, target.FullName + @"\" + dir.Name);
}
} public static void DeleteFile(string fileName)
{
try
{
FileInfo fi = new System.IO.FileInfo(fileName);
DeleteFile(fi);
}
catch (Exception ex)
{
PrintExcetpion($"删除文件失败-{fileName}", ex);
}
} public static void DeleteFile(FileInfo fi)
{
try
{
if (fi.Exists)
{
if (fi.Attributes.ToString().IndexOf("ReadOnly") != -)
fi.Attributes = System.IO.FileAttributes.Normal;
System.IO.File.Delete(fi.FullName); fi.Delete();
}
}
catch (Exception ex)
{
PrintExcetpion($"删除文件失败-{fi.FullName}", ex);
}
} public static void CreateDirectoyFromFileName(string fileName)
{
try
{
string path = Path.GetDirectoryName(fileName);
if (!new System.IO.DirectoryInfo(path).Exists)
System.IO.Directory.CreateDirectory(path);
}
catch (Exception ex)
{
PrintExcetpion($"创建文件夹失败-{fileName}", ex);
}
} public static void CreateDirectoyByFileName(string fileName)
{
try
{
string dir = Path.GetDirectoryName(fileName);
CreateDirectoy(dir);
}
catch (Exception ex)
{
PrintExcetpion($"由文件创建文件夹失败-{fileName}", ex);
}
} public static void CreateDirectoy(string dir)
{
try
{
if (!new System.IO.DirectoryInfo(dir).Exists)
System.IO.Directory.CreateDirectory(dir);
}
catch (Exception ex)
{
PrintExcetpion($"创建文件夹失败-{dir}", ex);
}
} public static string[] GetAllSubDirs(string root, SearchOption searchOption)
{
string[] all = null;
try
{
all = Directory.GetDirectories(root, "*", searchOption);
}
catch
{
// ignored
} return all;
} public static List<string> GetAllPureSubDirs(string root)
{
List<string> list = new List<string>();
try
{
string[] all = Directory.GetDirectories(root, "*", SearchOption.TopDirectoryOnly);
foreach (string path in all)
{
string s = System.IO.Path.GetFileName(path);
list.Add(s);
}
}
catch
{
// ignored
} return list;
} public static long GetFilesSize(string[] fileNames)
{
return fileNames.Sum(fileName => GetFileSize(fileName));
} public static long GetFileSize(string fileName)
{
if (!string.IsNullOrEmpty(fileName) && File.Exists(fileName))
return new FileInfo(fileName).Length; return ;
} /// <summary>
/// Files the content.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <returns></returns>
public static byte[] FileContent(string fileName)
{
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
try
{
byte[] buffur = new byte[fs.Length];
fs.Read(buffur, , (int)fs.Length); return buffur;
}
catch (Exception ex)
{
Console.WriteLine("读取文件字节流失败: {0}", ex.Message);
return null;
}
finally
{
if (fs != null)
{
//关闭资源
fs.Close();
}
}
} public static bool SaveString2File(string content, string fileName)
{
StreamWriter sw = null; try
{
CreateDirectoyFromFileName(fileName); sw = new StreamWriter(fileName);
sw.WriteLine(content);
}
catch (Exception ex)
{
PrintExcetpion($"保存内容错误-{fileName}", ex);
return false;
} if (sw != null)
sw.Close(); return true;
} public static string LoadStringFromFile(string fileName)
{
string content = string.Empty; StreamReader sr = null;
try
{
sr = new StreamReader(fileName,System.Text.Encoding.UTF8);
content = sr.ReadToEnd();
}
catch (Exception ex)
{
PrintExcetpion($"读取内容错误-{fileName}", ex);
} if (sr != null)
sr.Close(); return content;
} public static string GetLocalFileName(string lastPath, string displayName, string[] typeNames)
{
OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog(); // ofd.InitialDirectory = lastPath;
ofd.RestoreDirectory = true; // "动画(.flc;.fli;.gif;.swf)|*.flc;*.fli;*.gif;*.swf|Animation(.flc,.fli)|*.flc;*.fli|Gif89a(.gif)|*.gif|SWF(*.swf)|*.swf|"
// displayName + "(*.epub|All files (*.*)|*.*";
string filter = displayName + "("; filter = typeNames.Aggregate(filter, (current, ext) => current + ("." + ext + ";")); filter += ")|"; for (int i = ; i < typeNames.Length; i++)
{
filter += "*." + typeNames[i];
if (i < typeNames.Length - )
filter += ";";
} // filter += "|全部文件 (*.*)|*.*";
ofd.Filter = filter; return ofd.ShowDialog() != System.Windows.Forms.DialogResult.OK ? string.Empty : ofd.FileName;
} /// <summary>
/// 获取差异的文件列表
/// </summary>
/// <param name="srcDir"></param>
/// <param name="destDir"></param>
/// <returns></returns>
public static List<string> GetNotSameFiles(string srcDir, string destDir)
{
var oldData = new List<string>();
var newData = new List<string>();
new DirectoryInfo(srcDir).GetFiles().ToList().ForEach((f) =>
{
newData.Add(f.Name);
}); new DirectoryInfo(destDir).GetFiles().ToList().ForEach((f) =>
{
oldData.Add(f.Name);
}); //求交集
var dupComparer = new InlineComparer<string>((i1, i2) => i1.Equals(i2), i => i.GetHashCode());
var _IntersectData = oldData.Intersect(newData, dupComparer); if (_IntersectData == null || _IntersectData.Count() == )
return null; // 处理交集文件里可能有差异的内容。
var _files = new List<string>(); // 通过md5先过滤一部分数据 然后找到有差异的文件列表
_IntersectData.ToList().ForEach((s) =>
{
var o = Path.Combine(destDir, s);
var n = Path.Combine(srcDir, s); var omd5 = Md5FileHelper.MD5File(o);
var nmd5 = Md5FileHelper.MD5File(n); if (!omd5.Equals(nmd5))
{
_files.Add(s);
}
}); return _files;
} /// <summary>
/// 获取root文件夹下所有的文件,包含子文件夹中的文件
/// </summary>
/// <param name="root">文件夹路径</param>
/// <param name="extension">文件扩展名,默认为所有文件</param>
/// <returns>root文件夹下所有的文件的列表</returns>
public static List<string> GetAllFileList(string root, string extension = "")
{
if (Directory.Exists(root))
{
var dirList = GetAllSubDirs(root, SearchOption.AllDirectories).ToList();
dirList.Add(root); var list = new List<string>(); foreach (var dir in dirList)
{
DirectoryInfo dirInfo = new DirectoryInfo(dir);
dirInfo.GetFiles().ToList().ForEach(f =>
{
if (!string.IsNullOrWhiteSpace(extension))
{
if (f.Extension == (extension.Contains(".") ? extension : "." + extension))
{
list.Add(f.FullName);
}
}
else
{
list.Add(f.FullName);
}
});
} return list;
}
else
{
return null;
}
} public class InlineComparer<T> : IEqualityComparer<T>
{
private readonly Func<T, T, bool> getEquals;
private readonly Func<T, int> getHashCode; public InlineComparer(Func<T, T, bool> equals, Func<T, int> hashCode)
{
this.getEquals = equals;
this.getHashCode = hashCode;
} public bool Equals(T x, T y)
{
return this.getEquals(x, y);
} public int GetHashCode(T obj)
{
return this.getHashCode(obj);
}
}
}
}
---------------------
作者:代码养家
来源:CSDN
原文:https://blog.csdn.net/wangzl1163/article/details/79306885
版权声明:本文为博主原创文章,转载请附上博文链接!

FileHelper的更多相关文章

  1. 【无私分享:ASP.NET CORE 项目实战(第七章)】文件操作 FileHelper

    目录索引 [无私分享:ASP.NET CORE 项目实战]目录索引 简介 在程序设计中,我们很多情况下,会用到对文件的操作,在 上一个系列 中,我们有很多文件基本操作的示例,在Core中有一些改变,主 ...

  2. C# 最全的文件工具类FileHelper

    using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Lin ...

  3. [No0000DC]C# FileHelper 本地文件、文件夹操作类封装FileHelper

    using System; using System.Diagnostics; using System.IO; using System.Text; using Shared; namespace ...

  4. C#-FileHelper

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  5. 免费开源的DotNet任务调度组件Quartz.NET(.NET组件介绍之五)

    很多的软件项目中都会使用到定时任务.定时轮询数据库同步,定时邮件通知等功能..NET Framework具有“内置”定时器功能,通过System.Timers.Timer类.在使用Timer类需要面对 ...

  6. sqlyog导出json数据格式支持mysql数据转存mongodb

    <!-------------知识的力量是无限的(当然肯定还有更简单的方法)-----------!> 当我考虑将省市区三级联动数据从mysql转入mongodb时遇到了网上无直接插入mo ...

  7. 【无私分享:ASP.NET CORE 项目实战】目录索引

    简介 首先,我们的  [无私分享:从入门到精通ASP.NET MVC]   系列已经接近尾声,希望大家在这个过程中学到了一些思路和方法,而不仅仅是源码. 因为是第一次写博客,我感觉还是比较混乱的,其中 ...

  8. shell 带签名请求,yii 处理带签名的请求

    处理请求 class TestController extends Controller { public function init() { if(!YII_ENV_DEV){ throw new ...

  9. Thread.Sleep引发ThreadAbortException异常

    短信平台记录日志模块,是通过异步方式来记录的,即日志工具类里初始化一个Queue对象,公共的写日志方法的处理逻辑是把日志消息放到Queue里.构造器里设定一个死循环,不停的读队,然后把日志消息持久化到 ...

随机推荐

  1. acdream 1430 SETI 后缀数组+height分组

    这题昨天比赛的时候逗了,后缀想不出来,由于n^2的T了,就没往后缀数组想--并且之后解题的人又说用二分套二分来做.然后就更不会了-- 刚才看了题解,唉--原来题讲解n^2的也能够过,然后就--这样了! ...

  2. Django会话cookie&session

    任务描述:实现登录和退出 1.项目结构 2.源代码 urls.py from django.conf.urls import url from django.contrib import admin ...

  3. [Angular] Adding keyboard events to our control value accessor component

    One of the most important thing when building custom form component is adding accessbility support. ...

  4. php课程 6-23 mb_substr字符串截取怎么用

    php课程 6-23 mb_substr字符串截取怎么用 一.总结 一句话总结: 1.mb_substr字符串截取怎么用? 参数为:起始位置,个数 $str='我是小金,我是中国人!'; echo & ...

  5. EL表达式JSON应用

    由于之前在学校写的jsp页面都是夹杂着java代码的,所以之前写了个jsp,满满的<%%>和java代码,老师说那样太不美观了啊!!!要全部用EL表达式替代了.本人还是太笨了,弄了一上午才 ...

  6. spring boot打包后在tomcat无法访问静态资源问题

    我的spring boot项目中前端页面的资源引用 我的静态文件夹是 我的application.yml中资源路径配置了 同时我在WebMvcConfig中配置了addResourceHandlers ...

  7. 【13.91%】【codeforces 593D】Happy Tree Party

    time limit per test3 seconds memory limit per test256 megabytes inputstandard input outputstandard o ...

  8. Android Studio 2.3.1导出jar文件不能生成release解决办法

    升级了AS之后,在项目中的时候,有个需求需要把通过AS导出一个模块,需要以jar的形式导出来,研究了一下,按照网上的描述操作了一遍,不知道是AS版本问题还是自己操作问题,发现使用 ./gradlew ...

  9. mingw qt(可以去掉mingwm10.dll、libgcc_s_dw2-1.dll、libstdc++-6.dll的依赖,mingw默认都是动态链接gcc的库而TDM是静态链接gcc库,tdm版本更好用。用aspack压缩没有问题。qt本身不使用异常处理)good

    原文地址:mingw qt作者:孙1东 不使用Qt SDK,使用mingw编译qt源代码所遇问题及解决方法: configure -fast -release -no-exceptions -no-r ...

  10. 使用dom4j来处理xml的一些常用方法

    要使用dom4j读写XML文档,需要先下载dom4j包,dom4j官方网站在 http://www.dom4j.org/ 解开后有两个包,仅操作XML文档的话把dom4j-1.6.1.jar加入工程就 ...