class FileHelper
{ /// <summary>
/// 检验文件路径是否合法
/// </summary>
/// <param name="path">文件路径</param>
private static bool CheckPath(string path)
{
//正确格式:C:\Users\jcx\Desktop\Test.txt
string pattern = @"\w{1}:([\\].+)*.+\.\w{3,}";
Regex rg = new Regex(pattern);
return rg.IsMatch(path);
} /// <summary>
/// 创建一个新的文本文件
/// </summary>
/// <param name="path">文件路径</param>
/// <param name="content">写入到文本的内容</param>
public static void CreateNewTxtFile(string path,string content)
{
if (!CheckPath(path))
{
throw new Exception("文件路径不合法");
}
//存在则删除
if (File.Exists(path))
{
File.Delete(path);
} using (FileStream fs=new FileStream (path,FileMode.CreateNew,FileAccess.Write))
{
byte[] bt = Encoding.Default.GetBytes(content);
fs.Write(bt,,bt.Length); } //using
} /// <summary>
/// 读取文本文件
/// </summary>
/// <param name="path">文件路径</param>
/// <param name="readByte">指定每次读取字节数</param>
/// <returns>读取的全部文本内容</returns>
public static string ReadTxtFile(string path,long readByte)
{
if (!CheckPath(path))
{
throw new Exception("文件路径不合法");
} StringBuilder result = new StringBuilder();
using (FileStream fs=new FileStream (path,FileMode.Open,FileAccess.Read))
{
byte[] bt = new byte[readByte]; while (fs.Read(bt,,bt.Length)>) //每次只从文件中读取部分字节数,一点点读
{
string txt = Encoding.Default.GetString(bt); //解码转换成字符串
result.AppendLine(txt);
} } //using
return result.ToString(); } } class Program
{
static void Main(string[] args)
{ string path = @"C:\Users\jcx\Desktop\Test.txt"; FileHelper.CreateNewTxtFile(path, "好好努力");
string r = FileHelper.ReadTxtFile(path,); //2个字节为一个汉字,一个汉字一个汉字的读
Console.WriteLine(r); } // Main }

最新文章

  1. 2015弱校联盟(1) -J. Right turn
  2. NSData
  3. Textbox像百度一下实现下拉显示 z
  4. 自动FTP的小脚本
  5. 利用动画+div的前后切换实现轮播
  6. 测试WWW方案(反向代理,负载均衡,HTTP加速缓存)
  7. LVS Nginx HAProxy 优缺点
  8. unknow type name &#39;off64_t&#39;
  9. Intellij IDEA更新SVN没有提示语
  10. 【MySQL】查看支持的引擎show engines;
  11. Spring Cloud Ribbon——客户端负载均衡
  12. 【中间件安全】Tomcat 安全加固规范
  13. bzoj 1188
  14. Linux服务器svn与项目同步
  15. 使用dom4j解析xml为json对象
  16. OC 设计模式
  17. Office PPT如何切换到返回幻灯片
  18. Vue前端数据采集 埋点 追踪用户系列行为
  19. js中文逗号转英文逗号
  20. mysql下分组取关联表指定提示方法,类似于mssql中的cross apply

热门文章

  1. linux更改文件权限
  2. juqery dragsort使用遇到的问题
  3. java 集合框架小结
  4. PowerDesigner中利用数据库表反向生成PDM(jdk必须是32位)
  5. For update带来的思考
  6. HDU 2682 Tree(Kruskal算法求解MST)
  7. 快排,归并和Shell排序
  8. C#绑定数据
  9. 美图吴欣鸿:请不要叫我CEO
  10. EnyimMemcached(64位)使用实例