首页 > 代码库 > C# 常用文件操作
C# 常用文件操作
1 public class IoHelper 2 { 3 /// <summary> 4 /// 判断文件是否存在 5 /// </summary> 6 /// <param name="fileName">文件路径</param> 7 /// <returns>是否存在</returns> 8 public static bool Exists(string fileName) 9 { 10 if (fileName == null || fileName.Trim() == "") 11 { 12 return false; 13 } 14 return File.Exists(fileName); 15 } 16 17 18 /// <summary> 19 /// 创建文件夹 20 /// </summary> 21 /// <param name="dirName">文件夹名</param> 22 /// <returns></returns> 23 public static bool CreateDir(string dirName) 24 { 25 try 26 { 27 if (dirName == null) 28 throw new Exception("dirName"); 29 if (!Directory.Exists(dirName)) 30 { 31 Directory.CreateDirectory(dirName); 32 } 33 return true; 34 } 35 catch (Exception er) 36 { 37 throw new Exception(er.Message); 38 } 39 } 40 41 42 /// <summary> 43 /// 创建文件 44 /// </summary> 45 /// <param name="fileName">文件名</param> 46 /// <returns>创建失败返回false</returns> 47 public static bool CreateFile(string fileName) 48 { 49 try 50 { 51 if (File.Exists(fileName)) return false; 52 var fs = File.Create(fileName); 53 fs.Close(); 54 fs.Dispose(); 55 } 56 catch (IOException ioe) 57 { 58 throw new IOException(ioe.Message); 59 } 60 61 return true; 62 } 63 64 65 /// <summary> 66 /// 读文件内容,转化为字符类型 67 /// </summary> 68 /// <param name="fileName">文件路径</param> 69 /// <returns></returns> 70 public static string Read(string fileName) 71 { 72 if (!Exists(fileName)) 73 { 74 return null; 75 } 76 //将文件信息读入流中 77 using (var fs = new FileStream(fileName, FileMode.Open)) 78 { 79 return new StreamReader(fs).ReadToEnd(); 80 } 81 } 82 83 84 /// <summary> 85 /// 文件转化为Char[]数组 86 /// </summary> 87 /// <param name="fileName"></param> 88 /// <returns></returns> 89 public static char[] FileRead(string fileName) 90 { 91 if (!Exists(fileName)) 92 { 93 return null; 94 } 95 var byData = http://www.mamicode.com/new byte[1024]; 96 var charData = http://www.mamicode.com/new char[1024]; 97 try 98 { 99 var fileStream = new FileStream(fileName, FileMode.Open);100 fileStream.Seek(135, SeekOrigin.Begin);101 fileStream.Read(byData, 0, 1024);102 }103 catch (Exception ex)104 {105 throw new Exception(ex.Message);106 }107 var decoder = Encoding.UTF8.GetDecoder();108 decoder.GetChars(byData, 0, byData.Length, charData, 0);109 return charData;110 }111 112 113 114 /// <summary>115 /// 文件转化为byte[]116 /// </summary>117 /// <param name="fileName">文件路径</param>118 /// <returns></returns>119 public static byte[] ReadFile(string fileName)120 {121 FileStream pFileStream = null;122 try123 {124 pFileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);125 var r = new BinaryReader(pFileStream);126 //将文件指针设置到文件开127 r.BaseStream.Seek(0, SeekOrigin.Begin);128 var pReadByte = r.ReadBytes((int)r.BaseStream.Length);129 return pReadByte;130 }131 catch (Exception ex)132 {133 throw new Exception(ex.Message);134 135 }136 finally137 {138 if (pFileStream != null) pFileStream.Close();139 }140 }141 142 143 /// <summary>144 /// 将byte写入文件145 /// </summary>146 /// <param name="pReadByte">字节流</param>147 /// <param name="fileName">文件路径</param>148 /// <returns></returns>149 public static bool WriteFile(byte[] pReadByte, string fileName)150 {151 FileStream pFileStream = null;152 try153 {154 pFileStream = new FileStream(fileName, FileMode.OpenOrCreate);155 pFileStream.Write(pReadByte, 0, pReadByte.Length);156 }157 catch (Exception ex)158 {159 throw new Exception(ex.Message);160 }161 finally162 {163 if (pFileStream != null) pFileStream.Close();164 }165 return true;166 167 }168 169 public static string ReadLine(string fileName)170 {171 if (!Exists(fileName))172 {173 return null;174 }175 using (var fs = new FileStream(fileName, FileMode.Open))176 {177 return new StreamReader(fs).ReadLine();178 }179 }180 181 182 /// <summary>183 /// 写文件184 /// </summary>185 /// <param name="fileName">文件名</param>186 /// <param name="content">文件内容</param>187 /// <returns></returns>188 public static bool Write(string fileName, string content)189 {190 if (Exists(fileName) || content == null)191 {192 return false;193 }194 try195 {196 //将文件信息读入流中197 //初始化System.IO.FileStream类的新实例与指定路径和创建模式198 using (var fs = new FileStream(fileName, FileMode.OpenOrCreate))199 {200 //锁住流201 lock (fs)202 {203 if (!fs.CanWrite)204 {205 throw new System.Security.SecurityException("文件fileName=" + fileName + "是只读文件不能写入!");206 }207 208 var buffer = Encoding.Default.GetBytes(content);209 fs.Write(buffer, 0, buffer.Length);210 return true;211 }212 }213 }214 catch (IOException ioe)215 {216 throw new Exception(ioe.Message);217 }218 219 }220 221 222 /// <summary>223 /// 写入一行224 /// </summary>225 /// <param name="fileName">文件名</param>226 /// <param name="content">内容</param>227 /// <returns></returns>228 public static bool WriteLine(string fileName, string content)229 {230 if (string.IsNullOrEmpty(fileName))231 throw new ArgumentNullException(fileName);232 if (string.IsNullOrEmpty(content))233 throw new ArgumentNullException(content);234 using (var fs = new FileStream(fileName, FileMode.OpenOrCreate | FileMode.Append))235 {236 //锁住流237 lock (fs)238 {239 if (!fs.CanWrite)240 {241 throw new System.Security.SecurityException("文件fileName=" + fileName + "是只读文件不能写入!");242 }243 244 var sw = new StreamWriter(fs);245 sw.WriteLine(content);246 sw.Dispose();247 sw.Close();248 return true;249 }250 }251 }252 253 254 /// <summary>255 /// 复制目录256 /// </summary>257 /// <param name="fromDir">被复制的目录</param>258 /// <param name="toDir">复制到的目录</param>259 /// <returns></returns>260 public static bool CopyDir(DirectoryInfo fromDir, string toDir)261 {262 return CopyDir(fromDir, toDir, fromDir.FullName);263 }264 265 266 /// <summary>267 /// 复制目录268 /// </summary>269 /// <param name="fromDir">被复制的目录</param>270 /// <param name="toDir">复制到的目录</param>271 /// <returns></returns>272 public static bool CopyDir(string fromDir, string toDir)273 {274 if (fromDir == null || toDir == null)275 {276 throw new NullReferenceException("参数为空");277 }278 279 if (fromDir == toDir)280 {281 throw new Exception("两个目录都是" + fromDir);282 }283 284 if (!Directory.Exists(fromDir))285 {286 throw new IOException("目录fromDir=" + fromDir + "不存在");287 }288 289 var dir = new DirectoryInfo(fromDir);290 return CopyDir(dir, toDir, dir.FullName);291 }292 293 294 /// <summary>295 /// 复制目录296 /// </summary>297 /// <param name="fromDir">被复制的目录</param>298 /// <param name="toDir">复制到的目录</param>299 /// <param name="rootDir">被复制的根目录</param>300 /// <returns></returns>301 private static bool CopyDir(DirectoryInfo fromDir, string toDir, string rootDir)302 {303 foreach (var f in fromDir.GetFiles())304 {305 var filePath = toDir + f.FullName.Substring(rootDir.Length);306 var newDir = filePath.Substring(0, filePath.LastIndexOf("\\", StringComparison.Ordinal));307 CreateDir(newDir);308 File.Copy(f.FullName, filePath, true);309 }310 311 foreach (var dir in fromDir.GetDirectories())312 {313 CopyDir(dir, toDir, rootDir);314 }315 316 return true;317 }318 319 320 /// <summary>321 /// 删除文件322 /// </summary>323 /// <param name="fileName">文件的完整路径</param>324 /// <returns></returns>325 public static bool DeleteFile(string fileName)326 {327 try328 {329 if (!Exists(fileName)) return false;330 File.Delete(fileName);331 }332 catch (IOException ioe)333 {334 throw new ArgumentNullException(ioe.Message);335 }336 337 return true;338 }339 340 341 public static void DeleteDir(DirectoryInfo dir)342 {343 if (dir == null)344 {345 throw new NullReferenceException("目录不存在");346 }347 348 foreach (var d in dir.GetDirectories())349 {350 DeleteDir(d);351 }352 353 foreach (var f in dir.GetFiles())354 {355 DeleteFile(f.FullName);356 }357 358 dir.Delete();359 360 }361 362 363 /// <summary>364 /// 删除目录365 /// </summary>366 /// <param name="dir">指定目录</param>367 /// <param name="onlyDir">是否只删除目录</param>368 /// <returns></returns>369 public static bool DeleteDir(string dir, bool onlyDir)370 {371 if (dir == null || dir.Trim() == "")372 {373 throw new NullReferenceException("目录dir=" + dir + "不存在");374 }375 376 if (!Directory.Exists(dir))377 {378 return false;379 }380 381 var dirInfo = new DirectoryInfo(dir);382 if (dirInfo.GetFiles().Length == 0 && dirInfo.GetDirectories().Length == 0)383 {384 Directory.Delete(dir);385 return true;386 }387 388 389 if (!onlyDir)390 {391 return false;392 }393 DeleteDir(dirInfo);394 return true;395 }396 397 398 /// <summary>399 /// 在指定的目录中查找文件400 /// </summary>401 /// <param name="dir">目录</param>402 /// <param name="fileName">文件名</param>403 /// <returns></returns>404 public static bool FindFile(string dir, string fileName)405 {406 if (dir == null || dir.Trim() == "" || fileName == null || fileName.Trim() == "" || !Directory.Exists(dir))407 {408 return false;409 }410 411 //传入文件路径,获取当前文件对象412 var dirInfo = new DirectoryInfo(dir);413 return FindFile(dirInfo, fileName);414 415 }416 417 418 /// <summary>419 /// 返回文件是否存在420 /// </summary>421 /// <param name="dir"></param>422 /// <param name="fileName"></param>423 /// <returns></returns>424 public static bool FindFile(DirectoryInfo dir, string fileName)425 {426 foreach (var d in dir.GetDirectories())427 {428 if (File.Exists(d.FullName + "\\" + fileName))429 {430 return true;431 }432 FindFile(d, fileName);433 }434 435 return false;436 }437 438 439 /// <summary>440 /// 获取指定文件夹中的所有文件夹名称441 /// </summary>442 /// <param name="folderPath">路径</param>443 /// <returns></returns>444 public static List<string> FolderName(string folderPath)445 {446 var listFolderName = new List<string>();447 try448 {449 var info = new DirectoryInfo(folderPath);450 451 listFolderName.AddRange(info.GetDirectories().Select(nextFolder => nextFolder.Name));452 }453 catch (Exception er)454 {455 throw new Exception(er.Message);456 }457 458 return listFolderName;459 460 }461 462 463 /// <summary>464 /// 获取指定文件夹中的文件名称465 /// </summary>466 /// <param name="folderPath">路径</param>467 /// <returns></returns>468 public static List<string> FileName(string folderPath)469 {470 var listFileName = new List<string>();471 try472 {473 var info = new DirectoryInfo(folderPath);474 475 listFileName.AddRange(info.GetFiles().Select(nextFile => nextFile.Name));476 }477 catch (Exception er)478 {479 throw new Exception(er.Message);480 }481 482 return listFileName;483 }484 }
C# 压缩解压文件
方法一、调用WinRAR方式
1 /// <summary> 2 /// 利用 WinRAR 进行压缩 3 /// </summary> 4 /// <param name="path">将要被压缩的文件夹(绝对路径)</param> 5 /// <param name="rarPath">压缩后的 .rar 的存放目录(绝对路径)</param> 6 /// <param name="rarName">压缩文件的名称(包括后缀)</param> 7 /// <returns>true 或 false。压缩成功返回 true,反之,false。</returns> 8 public bool RAR(string path, string rarPath, string rarName) 9 { 10 bool flag = false; 11 string rarexe; //WinRAR.exe 的完整路径 12 RegistryKey regkey; //注册表键 13 Object regvalue; //键值 14 string cmd; //WinRAR 命令参数 15 ProcessStartInfo startinfo; 16 Process process; 17 try 18 { 19 regkey = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRAR.exe\shell\open\command"); 20 regvalue = http://www.mamicode.com/regkey.GetValue(""); // 键值为 "d:\Program Files\WinRAR\WinRAR.exe" "%1" 21 rarexe = regvalue.ToString(); 22 regkey.Close(); 23 rarexe = rarexe.Substring(1, rarexe.Length - 7); // d:\Program Files\WinRAR\WinRAR.exe 24 25 Directory.CreateDirectory(path); 26 path = "\"" + path + "\""; 27 //压缩命令,相当于在要压缩的文件夹(path)上点右键->WinRAR->添加到压缩文件->输入压缩文件名(rarName) 28 cmd = string.Format("a {0} {1} -ep1 -o+ -inul -r -ibck", 29 rarName, 30 path); 31 startinfo = new ProcessStartInfo(); 32 startinfo.FileName = rarexe; 33 startinfo.Arguments = cmd; //设置命令参数 34 startinfo.WindowStyle = ProcessWindowStyle.Hidden; //隐藏 WinRAR 窗口 35 36 startinfo.WorkingDirectory = rarPath; 37 process = new Process(); 38 process.StartInfo = startinfo; 39 process.Start(); 40 process.WaitForExit(); //无限期等待进程 winrar.exe 退出 41 if (process.HasExited) 42 { 43 flag = true; 44 } 45 process.Close(); 46 } 47 catch (Exception e) 48 { 49 throw e; 50 } 51 return flag; 52 } 53 /// <summary> 54 /// 利用 WinRAR 进行解压缩 55 /// </summary> 56 /// <param name="path">文件解压路径(绝对)</param> 57 /// <param name="rarPath">将要解压缩的 .rar 文件的存放目录(绝对路径)</param> 58 /// <param name="rarName">将要解压缩的 .rar 文件名(包括后缀)</param> 59 /// <returns>true 或 false。解压缩成功返回 true,反之,false。</returns> 60 public bool UnRAR(string path, string rarPath, string rarName) 61 { 62 bool flag = false; 63 string rarexe; 64 RegistryKey regkey; 65 Object regvalue; 66 string cmd; 67 ProcessStartInfo startinfo; 68 Process process; 69 try 70 { 71 regkey = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRAR.exe\shell\open\command"); 72 regvalue = http://www.mamicode.com/regkey.GetValue(""); 73 rarexe = regvalue.ToString(); 74 regkey.Close(); 75 rarexe = rarexe.Substring(1, rarexe.Length - 7); 76 77 Directory.CreateDirectory(path); 78 //解压缩命令,相当于在要压缩文件(rarName)上点右键->WinRAR->解压到当前文件夹 79 cmd = string.Format("x {0} {1} -y", 80 rarName, 81 path); 82 startinfo = new ProcessStartInfo(); 83 startinfo.FileName = rarexe; 84 startinfo.Arguments = cmd; 85 startinfo.WindowStyle = ProcessWindowStyle.Hidden; 86 87 startinfo.WorkingDirectory = rarPath; 88 process = new Process(); 89 process.StartInfo = startinfo; 90 process.Start(); 91 process.WaitForExit(); 92 if (process.HasExited) 93 { 94 flag = true; 95 } 96 process.Close(); 97 } 98 catch (Exception e) 99 {100 throw e;101 }102 return flag;103 }
注意:如果路径中有空格(如:D:\Program Files\)的话压缩解压就会出现问题,需要在path 和 rarName 上加双引号,如: path = "\"" + path + "\"";
方法二、使用C#压缩解压库
SharpCompress是一个开源的压缩解压库,可以对RAR,7Zip,Zip,Tar,GZip,BZip2进行处理。
官方网址:http://sharpcompress.codeplex.com/
使用例子:
1 //RAR文件解压缩: 2 using (Stream stream = File.OpenRead(@"C:\Code\sharpcompress.rar")) 3 { 4 var reader = ReaderFactory.Open(stream); 5 while (reader.MoveToNextEntry()) 6 { 7 if (!reader.Entry.IsDirectory) 8 { 9 Console.WriteLine(reader.Entry.FilePath);10 reader.WriteEntryToDirectory(@"C:\temp", ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);11 }12 }13 }14 15 16 //ZIP文件解压缩:17 var archive = ArchiveFactory.Open(@"C:\Code\sharpcompress\TestArchives\sharpcompress.zip");18 foreach (var entry in archive.Entries)19 {20 if (!entry.IsDirectory)21 {22 Console.WriteLine(entry.FilePath);23 entry.WriteToDirectory(@"C:\temp", ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);24 }25 }26 27 28 //压缩为ZIP文件:29 using (var archive = ZipArchive.Create())30 {31 archive.AddAllFromDirectoryEntry(@"C:\\source");32 archive.SaveTo("@C:\\new.zip");33 }34 35 36 37 //用Writer API创建ZIP文件 38 using (var zip = File.OpenWrite("C:\\test.zip"))39 using (var zipWriter = WriterFactory.Open(ArchiveType.Zip, zip))40 {41 foreach (var filePath in filesList)42 {43 zipWriter.Write(Path.GetFileName(file), filePath);44 }45 }46 47 48 //创建tar.bz249 using (Stream stream = File.OpenWrite(tarPath))50 using (var writer = WriterFactory.Open(ArchiveType.Tar, stream))51 {52 writer.WriteAll(filesPath, "*", SearchOption.AllDirectories);53 }54 using (Stream stream = File.OpenWrite(tarbz2Path))55 using (var writer = WriterFactory.Open(ArchiveType.BZip2, stream))56 {57 writer.Write("Tar.tar", tarPath);58 }
我们看到SharpCompress是没有压缩为rar的命令,因为所有RAR压缩文件都需要RAR作者的许可,你可以考虑压缩为zip或7zip,要不就使用WINRAR命令行压缩。
C# 常用文件操作
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。