C# 文件操作的工具类
根据查阅的资料对代码进行修改并完善备注后的结果。希望能对新手有所帮助。
1 using System; using System.IO;
namespace 文件操作类
{
public class FileHelper
{
/// <summary>
/// 判断文件是否存在
/// </summary>
/// <param name="filePath">文件全路径</param>
/// <returns></returns>
public static bool Exists(string filePath)
{
if (filePath == null || filePath.Trim() == "")
{
return false;
} if (File.Exists(filePath))
{
return true;
} return false;
} /// <summary>
/// 创建文件夹
/// </summary>
/// <param name="dirPath">文件夹路径</param>
/// <returns></returns>
public static bool CreateDir(string dirPath)
{
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
return true;
} /// <summary>
/// 创建文件
/// </summary>
/// <param name="filePath">文件路径</param>
/// <returns></returns>
public static bool CreateFile(string filePath)
{
if (!File.Exists(filePath))
{
FileStream fs = File.Create(filePath);
fs.Close();
fs.Dispose();
}
return true; } /// <summary>
/// 读文件内容
/// </summary>
/// <param name="filePath">文件路径</param>
/// <param name="encoding">编码格式</param>
/// <returns></returns>
public static string Read(string filePath,Encoding encoding)
{
if (!Exists(filePath))
{
return null;
}
//将文件信息读入流中
using (FileStream fs = new FileStream(filePath,FileMode.Open))
{
return new StreamReader(fs, encoding).ReadToEnd();
}
} /// <summary>
/// 读取文件的一行内容
/// </summary>
/// <param name="filePath">文件路径</param>
/// <param name="encoding">编码格式</param>
/// <returns></returns>
public static string ReadLine(string filePath, Encoding encoding)
{
if (!Exists(filePath))
{
return null;
}
using (FileStream fs = new FileStream(filePath, FileMode.Open))
{
return new StreamReader(fs, encoding).ReadLine();
}
} /// <summary>
/// 写文件
/// </summary>
/// <param name="filePath">文件路径</param>
/// <param name="content">文件内容</param>
/// <returns></returns>
public static bool Write(string filePath, string content)
{
if (!Exists(filePath) || content == null)
{
return false;
} //将文件信息读入流中
using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
{
lock (fs)//锁住流
{
if (!fs.CanWrite)
{
throw new System.Security.SecurityException("文件filePath=" + filePath + "是只读文件不能写入!");
} byte[] buffer = Encoding.Default.GetBytes(content);
fs.Write(buffer, , buffer.Length);
return true;
}
}
} /// <summary>
/// 写入一行
/// </summary>
/// <param name="filePath">文件路径</param>
/// <param name="content">内容</param>
/// <returns></returns>
public static bool WriteLine(string filePath, string content)
{
using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate | FileMode.Append))
{
lock (fs)
{
if (!fs.CanWrite)
{
throw new System.Security.SecurityException("文件filePath=" + filePath + "是只读文件不能写入!");
} StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(content);
sw.Dispose();
sw.Close();
return true;
}
}
} 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 + "不存在");
} DirectoryInfo 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)
{
string filePath = string.Empty;
foreach (FileInfo f in fromDir.GetFiles())
{
filePath = toDir + f.FullName.Substring(rootDir.Length);
string newDir = filePath.Substring(, filePath.LastIndexOf("\\"));
CreateDir(newDir);
File.Copy(f.FullName, filePath, true);
} foreach (DirectoryInfo dir in fromDir.GetDirectories())
{
CopyDir(dir, toDir, rootDir);
} return true;
} /// <summary>
/// 删除文件
/// </summary>
/// <param name="filePath">文件的完整路径</param>
/// <returns></returns>
public static bool DeleteFile(string filePath)
{
if (Exists(filePath))
{
File.Delete(filePath);
return true;
}
return false;
} public static void DeleteDir(DirectoryInfo dir)
{
if (dir == null)
{
throw new NullReferenceException("目录不存在");
} foreach (DirectoryInfo d in dir.GetDirectories())
{
DeleteDir(d);
} foreach (FileInfo 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;
} DirectoryInfo dirInfo = new DirectoryInfo(dir);
if (dirInfo.GetFiles().Length == && dirInfo.GetDirectories().Length == )
{
Directory.Delete(dir);
return true;
} if (!onlyDir)
{
return false;
}
else
{
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;
} DirectoryInfo dirInfo = new DirectoryInfo(dir);
return FindFile(dirInfo, fileName); } public static bool FindFile(DirectoryInfo dir, string fileName)
{
foreach (DirectoryInfo d in dir.GetDirectories())
{
if (File.Exists(d.FullName + "\\" + fileName))
{
return true;
}
FindFile(d, fileName);
} return false;
} }
}
转载请标出本博地址:http://www.cnblogs.com/codeToUp/p/4793153.html
C# 文件操作的工具类的更多相关文章
- java中文件操作的工具类
代码: package com.lky.pojo; import java.io.BufferedReader; import java.io.BufferedWriter; import java. ...
- Java中创建操作文件和文件夹的工具类
Java中创建操作文件和文件夹的工具类 FileUtils.java import java.io.BufferedInputStream; import java.io.BufferedOutput ...
- Java操作文件夹的工具类
Java操作文件夹的工具类 import java.io.File; public class DeleteDirectory { /** * 删除单个文件 * @param fileName 要删除 ...
- 自己封装的poi操作Excel工具类
自己封装的poi操作Excel工具类 在上一篇文章<使用poi读写Excel>中分享了一下poi操作Excel的简单示例,这次要分享一下我封装的一个Excel操作的工具类. 该工具类主要完 ...
- 文件上传工具类 UploadUtil.java
package com.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import ja ...
- Redis操作Set工具类封装,Java Redis Set命令封装
Redis操作Set工具类封装,Java Redis Set命令封装 >>>>>>>>>>>>>>>>& ...
- Redis操作List工具类封装,Java Redis List命令封装
Redis操作List工具类封装,Java Redis List命令封装 >>>>>>>>>>>>>>>> ...
- Redis操作Hash工具类封装,Redis工具类封装
Redis操作Hash工具类封装,Redis工具类封装 >>>>>>>>>>>>>>>>>> ...
- Redis操作字符串工具类封装,Redis工具类封装
Redis操作字符串工具类封装,Redis工具类封装 >>>>>>>>>>>>>>>>>>& ...
随机推荐
- 进击python第二篇:初识
入门拾遗 模块 模块用以导入python增强其功能扩展 1.使用 import [模块名] 导入,应用方式:模块. 函数,例: >>> import math >>> ...
- [題解](單調隊列dp)【2016noip福建夏令營】探險
P1917 -- 探险 时间限制:1000MS 内存限制:131072KB 题目描述(explore.cpp) π+e去遗迹探险,遗迹里有 N 个宝箱,有的装满了珠宝,有的装着废品. π+e ...
- POJ1470 LCA (Targan离线)
bryce1010模板 http://poj.org/problem?id=1470 /*伪代码 Tarjan(u)//marge和find为并查集合并函数和查找函数 { for each(u,v) ...
- 2016级萌新选拔赛BE题
#include<bits/stdc++.h> using namespace std; #define ll long long ll a[]; ll d[]; int main() { ...
- Python开发 第02课 Python 数据类型
1.Python 变量类型 变量存储在内存中的值.这就意味着在创建变量时会在内存中开辟一个空间.基于变量的数据类型,解释器会分配指定内存,并决定什么数据可以被存储在内存中.因此,变量可以指定不同的数据 ...
- 转 sqlplus 设置回闪 sqlplus下使用退格backspace回删出现^H的解决办法
转自 http://blog.csdn.net/chinadm123/article/details/44099351 1.进入sqlplus前设置回删 在进入sqlplus之前,在当前termina ...
- mysql添加用户并赋予权限命令
添加用户: create user 'gouge'@'localhost' identified by 'gouge'; 赋予权限: 给gouge 用户赋予所有test开头的数据库权限 (test% ...
- sourceTree免注册免登陆使用方法-Windows
安装sourceTree需要注册Google账号,而现在国内注册账号需要FQ,超级麻烦,所以还是免注册的号. 处理方法: 解决办法 在目录C:\Users\{youruser}\AppData\Loc ...
- nopCommerce - asp.net开源商城
nopcommerce官网 http://nopcommerce.codeplex.com/ nopCommerce is a open source e-commerce solution that ...
- ASP.Net MVC 控制@Html.DisplayFor日期显示格式
在做一個舊表的查詢頁時,遇到一個問題: 字段在db里存儲的是DATETIME,但保存的值只有日期,沒有時間數據,比如2018/2/26 0:00:00,顯示出來比較難看, 當然也可以做一個ViewMo ...