C# 常用文件操作
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# 常用文件操作的更多相关文章
- python 历险记(三)— python 的常用文件操作
目录 前言 文件 什么是文件? 如何在 python 中打开文件? python 文件对象有哪些属性? 如何读文件? read() readline() 如何写文件? 如何操作文件和目录? 强大的 o ...
- Python之常用文件操作
Python之常用文件操作
- Unix/Linux常用文件操作
Unix/Linux常用文件操作 秘籍:man命令是Unix/Linux中最常用的命令,因为命令行命令过多,我相信每个人都会经常忘记某些命令的用法,man命令就可以显示一个命令的所有选项,参数和说明, ...
- 真香!Python十大常用文件操作,轻松办公
日常对于批量处理文件的需求非常多,用Python写脚本可以非常方便地实现,但在这过程中难免会和文件打交道,第一次做会有很多文件的操作无从下手,只能找度娘. 本篇文章整理了10个Python中最常用到的 ...
- Java常用文件操作-2
上篇文章记录了常用的文件操作,这里记录下通过SSH服务器操作Linux服务器的指定路径下的文件. 这里用到了第三方jar包 jsch-0.1.53.jar, jsch-api 1.删除服务器上指定路径 ...
- 【阅读笔记】《C程序员 从校园到职场》第六章 常用文件操作函数 (Part 1)
参考链接:https://blog.csdn.net/zhouzhaoxiong1227/article/details/24926023 让你提前认识软件开发(18):C语言中常用的文件操作函数总结 ...
- 文件操作(FILE)与常用文件操作函数
文件 1.文件基本概念 C程序把文件分为ASCII文件和二进制文件,ASCII文件又称文本文件,二进制文件和文本文件(也称ASCII码文件)二进制文件中,数值型数据是以二进制形式存储的, 而在文本文件 ...
- Java常用文件操作-1
在我们的实际工作中经常会用到的文件操作,再此,将工作中碰到的做一个记录,以便日后查看. 1.复制文件夹到新文件夹下 /** * 复制文件夹下所有文件到指定路径 *@param oldPath *@pa ...
- C#File类常用文件操作以及一个模拟的控制台文件管理系统
重温一下C#中File类的一些基本操作: File类,是一个静态类,主要是来提供一些函数库用的. 使用时需要引入System.IO命名空间. 一.常用操作: 1.创建文件方法 //参数1:要创建的文件 ...
- 常用文件操作 分类: C# 2014-10-14 16:18 108人阅读 评论(0) 收藏
界面图: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; ...
随机推荐
- 正则表达式 获取字符串内提取图片URL字符串
#region 获取字符串内提取图片URL字符串 /// <summary> /// 获取字符串内提取图片URL字符串 /// </summary> /// <param ...
- uboot无法引导uImage错误及其解决方法
先编译友善提供的linux内核: make ARCH=arm mini2440_defconfigmake CROSS_COMPILE=arm-linux- uImage 在arch/arm/boot ...
- OC中NSSet去重细节
我们都知道,NSSet在存储数据时,不允许存储相同数据?那么,这里的相同该如何理解呢? 很多人都简单的理解为按照其存储对象的内存地址进行评判.其实不然.经过个人实验证明:当类型为NSString,NS ...
- cocos2dx打飞机项目笔记三:HeroLayer类和坐标系
HeroLayer类主要是处理hero的一些相关东西,以及调用bulletLayer的一些方法,因为子弹是附属于hero的~~ HeroLayer 类的成员如下: class HeroLayer : ...
- kvm初体验——linux之kvm安装及使用qemu工具安装系统【转】
本文转载自:https://blog.csdn.net/Heimerdinger_Feng/article/details/79119445 一.安装虚拟机之前先升级软件仓库 sudo apt-get ...
- Bootstrap3组件--2
目录 1. 分页 2. 标签 3. 徽章 4. 巨幕 5. 页头 6. 缩略图 7. 警告框 8. 进度条 9. 列表组 10. 面板 11.Well 1. 分页 <!doctype html& ...
- 网络最大流的(Edmond Karp)算法
容量网络:在有向图D=(V,A),指定一个点为发点,记作 s,指定另一个点为收点,记作 t,其余点叫作中间点.对于A的每条弧(Vi,Ai),都对应一个权数 C ≥0,称为弧(Vi , Ai)的容量,将 ...
- ElasticSearch入门常用命令
基于开源项目MyAlice智能客服学习ElasticSearch https://github.com/hpgary/MyAlice/wiki/%E7%AC%AC01%E7%AB%A0%E5%AE%8 ...
- 汇编笔记 RET
assume cs:code,ss:stack stack segment db dup() stack ends code segment mov ax,4c00h int 21h start: m ...
- jsp:<c:redirect> 和<c:param> 标签
redirect 标签使用来进行页面之间的重定向,它和传统 JSP 程序中的<jsp:redirect>标记功能相类似.param 标签是和 redirect 一起使用的,它用来进行参数值 ...