public class IoHelper
{
/// <summary>
/// 判断文件是否存在
/// </summary>
/// <param name="fileName">文件路径</param>
/// <returns>是否存在</returns>
public static bool Exists(string fileName)
{
if (fileName == null || fileName.Trim() == "")
{
return false;
}
return File.Exists(fileName);
} /// <summary>
/// 创建文件夹
/// </summary>
/// <param name="dirName">文件夹名</param>
/// <returns></returns>
public static bool CreateDir(string dirName)
{
try
{
if (dirName == null)
throw new Exception("dirName");
if (!Directory.Exists(dirName))
{
Directory.CreateDirectory(dirName);
}
return true;
}
catch (Exception er)
{
throw new Exception(er.Message);
}
} /// <summary>
/// 创建文件
/// </summary>
/// <param name="fileName">文件名</param>
/// <returns>创建失败返回false</returns>
public static bool CreateFile(string fileName)
{
try
{
if (File.Exists(fileName)) return false;
var fs = File.Create(fileName);
fs.Close();
fs.Dispose();
}
catch (IOException ioe)
{
throw new IOException(ioe.Message);
} return true;
} /// <summary>
/// 读文件内容,转化为字符类型
/// </summary>
/// <param name="fileName">文件路径</param>
/// <returns></returns>
public static string Read(string fileName)
{
if (!Exists(fileName))
{
return null;
}
//将文件信息读入流中
using (var fs = new FileStream(fileName, FileMode.Open))
{
return new StreamReader(fs).ReadToEnd();
}
} /// <summary>
/// 文件转化为Char[]数组
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static char[] FileRead(string fileName)
{
if (!Exists(fileName))
{
return null;
}
var byData = new byte[];
var charData = new char[];
try
{
var fileStream = new FileStream(fileName, FileMode.Open);
fileStream.Seek(, SeekOrigin.Begin);
fileStream.Read(byData, , );
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
var decoder = Encoding.UTF8.GetDecoder();
decoder.GetChars(byData, , byData.Length, charData, );
return charData;
} /// <summary>
/// 文件转化为byte[]
/// </summary>
/// <param name="fileName">文件路径</param>
/// <returns></returns>
public static byte[] ReadFile(string fileName)
{
FileStream pFileStream = null;
try
{
pFileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
var r = new BinaryReader(pFileStream);
//将文件指针设置到文件开
r.BaseStream.Seek(, SeekOrigin.Begin);
var pReadByte = r.ReadBytes((int)r.BaseStream.Length);
return pReadByte;
}
catch (Exception ex)
{
throw new Exception(ex.Message); }
finally
{
if (pFileStream != null) pFileStream.Close();
}
} /// <summary>
/// 将byte写入文件
/// </summary>
/// <param name="pReadByte">字节流</param>
/// <param name="fileName">文件路径</param>
/// <returns></returns>
public static bool WriteFile(byte[] pReadByte, string fileName)
{
FileStream pFileStream = null;
try
{
pFileStream = new FileStream(fileName, FileMode.OpenOrCreate);
pFileStream.Write(pReadByte, , pReadByte.Length);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
if (pFileStream != null) pFileStream.Close();
}
return true; } public static string ReadLine(string fileName)
{
if (!Exists(fileName))
{
return null;
}
using (var fs = new FileStream(fileName, FileMode.Open))
{
return new StreamReader(fs).ReadLine();
}
} /// <summary>
/// 写文件
/// </summary>
/// <param name="fileName">文件名</param>
/// <param name="content">文件内容</param>
/// <returns></returns>
public static bool Write(string fileName, string content)
{
if (Exists(fileName) || content == null)
{
return false;
}
try
{
//将文件信息读入流中
//初始化System.IO.FileStream类的新实例与指定路径和创建模式
using (var fs = new FileStream(fileName, FileMode.OpenOrCreate))
{
//锁住流
lock (fs)
{
if (!fs.CanWrite)
{
throw new System.Security.SecurityException("文件fileName=" + fileName + "是只读文件不能写入!");
} var buffer = Encoding.Default.GetBytes(content);
fs.Write(buffer, , buffer.Length);
return true;
}
}
}
catch (IOException ioe)
{
throw new Exception(ioe.Message);
} } /// <summary>
/// 写入一行
/// </summary>
/// <param name="fileName">文件名</param>
/// <param name="content">内容</param>
/// <returns></returns>
public static bool WriteLine(string fileName, string content)
{
if (string.IsNullOrEmpty(fileName))
throw new ArgumentNullException(fileName);
if (string.IsNullOrEmpty(content))
throw new ArgumentNullException(content);
using (var fs = new FileStream(fileName, FileMode.OpenOrCreate | FileMode.Append))
{
//锁住流
lock (fs)
{
if (!fs.CanWrite)
{
throw new System.Security.SecurityException("文件fileName=" + fileName + "是只读文件不能写入!");
} var sw = new StreamWriter(fs);
sw.WriteLine(content);
sw.Dispose();
sw.Close();
return true;
}
}
} /// <summary>
/// 复制目录
/// </summary>
/// <param name="fromDir">被复制的目录</param>
/// <param name="toDir">复制到的目录</param>
/// <returns></returns>
public static bool CopyDir(DirectoryInfo fromDir, string toDir)
{
return CopyDir(fromDir, toDir, fromDir.FullName);
} /// <summary>
/// 复制目录
/// </summary>
/// <param name="fromDir">被复制的目录</param>
/// <param name="toDir">复制到的目录</param>
/// <returns></returns>
public static bool CopyDir(string fromDir, string toDir)
{
if (fromDir == null || toDir == null)
{
throw new NullReferenceException("参数为空");
} if (fromDir == toDir)
{
throw new Exception("两个目录都是" + fromDir);
} if (!Directory.Exists(fromDir))
{
throw new IOException("目录fromDir=" + fromDir + "不存在");
} var dir = new DirectoryInfo(fromDir);
return CopyDir(dir, toDir, dir.FullName);
} /// <summary>
/// 复制目录
/// </summary>
/// <param name="fromDir">被复制的目录</param>
/// <param name="toDir">复制到的目录</param>
/// <param name="rootDir">被复制的根目录</param>
/// <returns></returns>
private static bool CopyDir(DirectoryInfo fromDir, string toDir, string rootDir)
{
foreach (var f in fromDir.GetFiles())
{
var filePath = toDir + f.FullName.Substring(rootDir.Length);
var newDir = filePath.Substring(, filePath.LastIndexOf("\\", StringComparison.Ordinal));
CreateDir(newDir);
File.Copy(f.FullName, filePath, true);
} foreach (var dir in fromDir.GetDirectories())
{
CopyDir(dir, toDir, rootDir);
} return true;
} /// <summary>
/// 删除文件
/// </summary>
/// <param name="fileName">文件的完整路径</param>
/// <returns></returns>
public static bool DeleteFile(string fileName)
{
try
{
if (!Exists(fileName)) return false;
File.Delete(fileName);
}
catch (IOException ioe)
{
throw new ArgumentNullException(ioe.Message);
} return true;
} public static void DeleteDir(DirectoryInfo dir)
{
if (dir == null)
{
throw new NullReferenceException("目录不存在");
} foreach (var d in dir.GetDirectories())
{
DeleteDir(d);
} foreach (var f in dir.GetFiles())
{
DeleteFile(f.FullName);
} dir.Delete(); } /// <summary>
/// 删除目录
/// </summary>
/// <param name="dir">指定目录</param>
/// <param name="onlyDir">是否只删除目录</param>
/// <returns></returns>
public static bool DeleteDir(string dir, bool onlyDir)
{
if (dir == null || dir.Trim() == "")
{
throw new NullReferenceException("目录dir=" + dir + "不存在");
} if (!Directory.Exists(dir))
{
return false;
} var dirInfo = new DirectoryInfo(dir);
if (dirInfo.GetFiles().Length == && dirInfo.GetDirectories().Length == )
{
Directory.Delete(dir);
return true;
} if (!onlyDir)
{
return false;
}
DeleteDir(dirInfo);
return true;
} /// <summary>
/// 在指定的目录中查找文件
/// </summary>
/// <param name="dir">目录</param>
/// <param name="fileName">文件名</param>
/// <returns></returns>
public static bool FindFile(string dir, string fileName)
{
if (dir == null || dir.Trim() == "" || fileName == null || fileName.Trim() == "" || !Directory.Exists(dir))
{
return false;
} //传入文件路径,获取当前文件对象
var dirInfo = new DirectoryInfo(dir);
return FindFile(dirInfo, fileName); } /// <summary>
/// 返回文件是否存在
/// </summary>
/// <param name="dir"></param>
/// <param name="fileName"></param>
/// <returns></returns>
public static bool FindFile(DirectoryInfo dir, string fileName)
{
foreach (var d in dir.GetDirectories())
{
if (File.Exists(d.FullName + "\\" + fileName))
{
return true;
}
FindFile(d, fileName);
} return false;
} /// <summary>
/// 获取指定文件夹中的所有文件夹名称
/// </summary>
/// <param name="folderPath">路径</param>
/// <returns></returns>
public static List<string> FolderName(string folderPath)
{
var listFolderName = new List<string>();
try
{
var info = new DirectoryInfo(folderPath); listFolderName.AddRange(info.GetDirectories().Select(nextFolder => nextFolder.Name));
}
catch (Exception er)
{
throw new Exception(er.Message);
} return listFolderName; } /// <summary>
/// 获取指定文件夹中的文件名称
/// </summary>
/// <param name="folderPath">路径</param>
/// <returns></returns>
public static List<string> FileName(string folderPath)
{
var listFileName = new List<string>();
try
{
var info = new DirectoryInfo(folderPath); listFileName.AddRange(info.GetFiles().Select(nextFile => nextFile.Name));
}
catch (Exception er)
{
throw new Exception(er.Message);
} return listFileName;
}
} C#实现文件遍历拷贝
  public static bool CopyDirectory(string pathSrc, string pathDst)
{
if(!Directory.Exists(pathSrc))
{
return false;
} CreateFullPath(pathDst); DirectoryInfo directorySrc = new DirectoryInfo(pathSrc);
DirectoryInfo directoryDst = new DirectoryInfo(pathDst); CopyDirectory(directorySrc, directoryDst);
return true;
} private static void CopyDirectory(DirectoryInfo srcDictionary, DirectoryInfo dstDictionary)
{
FileInfo[] srcFiles = srcDictionary.GetFiles();
foreach(FileInfo srcFile in srcFiles)
{
File.Copy(srcFile.FullName, Path.Combine(dstDictionary.FullName, srcFile.Name), true);
} DirectoryInfo[] directorySrcArray = srcDictionary.GetDirectories();
foreach(DirectoryInfo directorySrc in directorySrcArray)
{
string dstDirectoryFullPath = Path.Combine(dstDictionary.FullName, directorySrc.Name);
DirectoryInfo directoryDst = new DirectoryInfo(dstDirectoryFullPath); CreateFullPath(directoryDst.FullName); CopyDirectory(directorySrc, directoryDst);
}
} private static void CreateFullPath(string fullPath)
{
if (!Directory.Exists(fullPath))
{
Directory.CreateDirectory(fullPath);
}
}

C# 压缩解压文件

方法一、调用WinRAR方式

 /// <summary>
/// 利用 WinRAR 进行压缩
/// </summary>
/// <param name="path">将要被压缩的文件夹(绝对路径)</param>
/// <param name="rarPath">压缩后的 .rar 的存放目录(绝对路径)</param>
/// <param name="rarName">压缩文件的名称(包括后缀)</param>
/// <returns>true 或 false。压缩成功返回 true,反之,false。</returns>
public bool RAR(string path, string rarPath, string rarName)
{
bool flag = false;
string rarexe; //WinRAR.exe 的完整路径
RegistryKey regkey; //注册表键
Object regvalue; //键值
string cmd; //WinRAR 命令参数
ProcessStartInfo startinfo;
Process process;
try
{
regkey = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRAR.exe\shell\open\command");
regvalue = regkey.GetValue(""); // 键值为 "d:\Program Files\WinRAR\WinRAR.exe" "%1"
rarexe = regvalue.ToString();
regkey.Close();
rarexe = rarexe.Substring(, rarexe.Length - ); // d:\Program Files\WinRAR\WinRAR.exe Directory.CreateDirectory(path);
path = "\"" + path + "\"";
//压缩命令,相当于在要压缩的文件夹(path)上点右键->WinRAR->添加到压缩文件->输入压缩文件名(rarName)
cmd = string.Format("a {0} {1} -ep1 -o+ -inul -r -ibck",
rarName,
path);
startinfo = new ProcessStartInfo();
startinfo.FileName = rarexe;
startinfo.Arguments = cmd; //设置命令参数
startinfo.WindowStyle = ProcessWindowStyle.Hidden; //隐藏 WinRAR 窗口 startinfo.WorkingDirectory = rarPath;
process = new Process();
process.StartInfo = startinfo;
process.Start();
process.WaitForExit(); //无限期等待进程 winrar.exe 退出
if (process.HasExited)
{
flag = true;
}
process.Close();
}
catch (Exception e)
{
throw e;
}
return flag;
}
/// <summary>
/// 利用 WinRAR 进行解压缩
/// </summary>
/// <param name="path">文件解压路径(绝对)</param>
/// <param name="rarPath">将要解压缩的 .rar 文件的存放目录(绝对路径)</param>
/// <param name="rarName">将要解压缩的 .rar 文件名(包括后缀)</param>
/// <returns>true 或 false。解压缩成功返回 true,反之,false。</returns>
public bool UnRAR(string path, string rarPath, string rarName)
{
bool flag = false;
string rarexe;
RegistryKey regkey;
Object regvalue;
string cmd;
ProcessStartInfo startinfo;
Process process;
try
{
regkey = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRAR.exe\shell\open\command");
regvalue = regkey.GetValue("");
rarexe = regvalue.ToString();
regkey.Close();
rarexe = rarexe.Substring(, rarexe.Length - ); Directory.CreateDirectory(path);
//解压缩命令,相当于在要压缩文件(rarName)上点右键->WinRAR->解压到当前文件夹
cmd = string.Format("x {0} {1} -y",
rarName,
path);
startinfo = new ProcessStartInfo();
startinfo.FileName = rarexe;
startinfo.Arguments = cmd;
startinfo.WindowStyle = ProcessWindowStyle.Hidden; startinfo.WorkingDirectory = rarPath;
process = new Process();
process.StartInfo = startinfo;
process.Start();
process.WaitForExit();
if (process.HasExited)
{
flag = true;
}
process.Close();
}
catch (Exception e)
{
throw e;
}
return flag;
}

注意:如果路径中有空格(如:D:\Program Files\)的话压缩解压就会出现问题,需要在path 和 rarName 上加双引号,如: path = "\"" + path + "\"";

方法二、使用C#压缩解压库

SharpCompress是一个开源的压缩解压库,可以对RAR,7Zip,Zip,Tar,GZip,BZip2进行处理。

官方网址:http://sharpcompress.codeplex.com/

使用例子:

 //RAR文件解压缩:
using (Stream stream = File.OpenRead(@"C:\Code\sharpcompress.rar"))
{
var reader = ReaderFactory.Open(stream);
while (reader.MoveToNextEntry())
{
if (!reader.Entry.IsDirectory)
{
Console.WriteLine(reader.Entry.FilePath);
reader.WriteEntryToDirectory(@"C:\temp", ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
}
}
} //ZIP文件解压缩:
var archive = ArchiveFactory.Open(@"C:\Code\sharpcompress\TestArchives\sharpcompress.zip");
foreach (var entry in archive.Entries)
{
if (!entry.IsDirectory)
{
Console.WriteLine(entry.FilePath);
entry.WriteToDirectory(@"C:\temp", ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
}
} //压缩为ZIP文件:
using (var archive = ZipArchive.Create())
{
archive.AddAllFromDirectoryEntry(@"C:\\source");
archive.SaveTo("@C:\\new.zip");
} //用Writer API创建ZIP文件
using (var zip = File.OpenWrite("C:\\test.zip"))
using (var zipWriter = WriterFactory.Open(ArchiveType.Zip, zip))
{
foreach (var filePath in filesList)
{
zipWriter.Write(Path.GetFileName(file), filePath);
}
} //创建tar.bz2
using (Stream stream = File.OpenWrite(tarPath))
using (var writer = WriterFactory.Open(ArchiveType.Tar, stream))
{
writer.WriteAll(filesPath, "*", SearchOption.AllDirectories);
}
using (Stream stream = File.OpenWrite(tarbz2Path))
using (var writer = WriterFactory.Open(ArchiveType.BZip2, stream))
{
writer.Write("Tar.tar", tarPath);
}

我们看到SharpCompress是没有压缩为rar的命令,因为所有RAR压缩文件都需要RAR作者的许可,你可以考虑压缩为zip或7zip,要不就使用WINRAR命令行压缩。

C# 常用文件操作的更多相关文章

  1. python 历险记(三)— python 的常用文件操作

    目录 前言 文件 什么是文件? 如何在 python 中打开文件? python 文件对象有哪些属性? 如何读文件? read() readline() 如何写文件? 如何操作文件和目录? 强大的 o ...

  2. Python之常用文件操作

    Python之常用文件操作

  3. Unix/Linux常用文件操作

    Unix/Linux常用文件操作 秘籍:man命令是Unix/Linux中最常用的命令,因为命令行命令过多,我相信每个人都会经常忘记某些命令的用法,man命令就可以显示一个命令的所有选项,参数和说明, ...

  4. 真香!Python十大常用文件操作,轻松办公

    日常对于批量处理文件的需求非常多,用Python写脚本可以非常方便地实现,但在这过程中难免会和文件打交道,第一次做会有很多文件的操作无从下手,只能找度娘. 本篇文章整理了10个Python中最常用到的 ...

  5. Java常用文件操作-2

    上篇文章记录了常用的文件操作,这里记录下通过SSH服务器操作Linux服务器的指定路径下的文件. 这里用到了第三方jar包 jsch-0.1.53.jar, jsch-api 1.删除服务器上指定路径 ...

  6. 【阅读笔记】《C程序员 从校园到职场》第六章 常用文件操作函数 (Part 1)

    参考链接:https://blog.csdn.net/zhouzhaoxiong1227/article/details/24926023 让你提前认识软件开发(18):C语言中常用的文件操作函数总结 ...

  7. 文件操作(FILE)与常用文件操作函数

    文件 1.文件基本概念 C程序把文件分为ASCII文件和二进制文件,ASCII文件又称文本文件,二进制文件和文本文件(也称ASCII码文件)二进制文件中,数值型数据是以二进制形式存储的, 而在文本文件 ...

  8. Java常用文件操作-1

    在我们的实际工作中经常会用到的文件操作,再此,将工作中碰到的做一个记录,以便日后查看. 1.复制文件夹到新文件夹下 /** * 复制文件夹下所有文件到指定路径 *@param oldPath *@pa ...

  9. C#File类常用文件操作以及一个模拟的控制台文件管理系统

    重温一下C#中File类的一些基本操作: File类,是一个静态类,主要是来提供一些函数库用的. 使用时需要引入System.IO命名空间. 一.常用操作: 1.创建文件方法 //参数1:要创建的文件 ...

  10. 常用文件操作 分类: C# 2014-10-14 16:18 108人阅读 评论(0) 收藏

    界面图: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; ...

随机推荐

  1. 九、搭建备份服务器 使用rsync服务

    简介 Rsync是开源快速.多功能,可以实现全量和增量的本地或者远程数据同步备份的优秀工具.增量备份效率更高,可以同步内容也可以同步属性 [root@backup-41 ~]# rpm -qa rsy ...

  2. memcpy与memmove

    函数原型: void* memcpy(void *dst,void const *src,size_t count) void* memmove(void *dst,void const *src,s ...

  3. 高通平台MSM8916LCM模块移植(一)-bootloader部分【转】

    本文转载自:http://www.mobile-open.com/2016/970947.html 高通平台中的bootloader叫做LK(Little Kernel,对于LCM来说LK部分相当重要 ...

  4. java异常和错误类总结(2016.5)

    看到以前2016.5.写的一点笔记,拿过来放在一起. java异常和错误类总结 最近由于考试和以前的面试经常会遇到java当中异常类的继承层次的问题,弄得非常头大,因为java的异常实在是有点多,很难 ...

  5. HDU 汉诺塔系列

    做了这一系列题,表示对汉诺塔与这一系列递推理解加深了 经典汉诺塔:1,2,...,n表示n个盘子,数字大盘子就大,n个盘子放在第1根柱子上,按照从上到下 从小到大的顺序排放,过程中每次大盘都不能放在小 ...

  6. 【转】jQuery对象与DOM对象之间的转换方法

    刚开始学习jquery,可能一时会分不清楚哪些是jQuery对象,哪些是DOM对象.至于DOM对象不多解释,我们接触的太多了,下面重点介绍一下jQuery,以及两者相互间的转换. 什么是jQuery对 ...

  7. MYSQL进阶学习笔记一:MySQL编码设定,会话变量和全局变量!(视频序号:进阶_1-3)

    知识点一:MySQL编码设定(1-2) 服务器编码设定: 查看MySQL服务器端的编码格式: SHOW VARIABLES LIKE ‘char%’; 设定编码格式: SET NAMES ‘utf8’ ...

  8. Intel Code Challenge Elimination Round (Div.1 + Div.2, combined) D. Generating Sets 贪心+优先队列

    D. Generating Sets time limit per test 2 seconds memory limit per test 256 megabytes input standard ...

  9. 不理解use explanatory variables

  10. 闲聊SEO

    SEO 1. SEO 搜索引擎优化 免费(Baidu,Google) SEM 搜索引擎营销 收费 2. IP 独立IP访问的用户 PV 页面的点击量 UV 独立访客数 3. 搜索引擎蜘蛛 权重 去让搜 ...