asp.net 读写文件的方法!!!
2011-06-08 13:02
281 查看
读写文件是在做项目是常用的功能,有很多实现的方法,我提供最常用的方法来发布一下,供出学者参考。
1.写入文件
2.读取文件
3.另一种写入文件
学习交流!
1.写入文件
/// <summary> /// 写入文件 /// </summary> /// <param name="Content"></param> /// <param name="FileSavePath"></param> public static void WriteFile(string Content, string FileSavePath) { if (File.Exists(FileSavePath)) { File.Delete(FileSavePath); } FileStream fs = File.Create(FileSavePath); Byte[] bContent = System.Text.Encoding.UTF8.GetBytes(Content); fs.Write(bContent, 0, bContent.Length); fs.Close(); fs.Dispose(); }
2.读取文件
/// <summary> /// 获取文件的内容 /// </summary> /// <param name="file"></param> /// <returns></returns> public static string GetFileContent(string file) { FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read); StreamReader sr = new StreamReader(fs, Encoding.UTF8); StringBuilder output = new StringBuilder(); string rl; while ((rl = sr.ReadLine()) != null) { output.Append(rl + "<br>"); } sr.Close(); fs.Close(); return output.ToString(); }
3.另一种写入文件
/// <summary> /// 写入XML方法 /// </summary> /// <param name="input">要写入XML文件的内容</param> /// <param name="path">相对路径就OK了,不用绝对路径</param> public void WriteLogFile(string input,string path) { ///指定日志文件的目录 string fname = Server.MapPath(path) ; ///定义文件信息对象 FileInfo finfo = new FileInfo(fname); ///判断文件是否存在 if (finfo.Exists) { ///删除该文件 finfo.Delete(); } ///创建只写文件流 using (FileStream fs = finfo.OpenWrite()) { ///根据上面创建的文件流创建写数据流 StreamWriter w = new StreamWriter(fs); ///设置写数据流的起始位置为文件流的末尾 w.BaseStream.Seek(0, SeekOrigin.End); ///写入“文件内容 ” w.Write(input); ///删除缓存 w.Flush(); ///关闭流 w.Close(); }
学习交流!
相关文章推荐
- asp.net读写配置文件方法
- 在asp.net中读取XML文件信息的4种方法(转载)
- asp.net上传文件时提示,不支持给定路径的格式解决方法
- ASP.NET文件上传控件Uploadify的使用方法
- asp.net 2.0 读写配置文件
- 在ASP.NET中实现多文件上传的方法
- Asp.NET导出Excel文件乱码解决方法
- asp.net INI文件读写类
- ASP.NET中cookie读写方法介绍本
- 在ASP.NET中,IE与Firefox下载文件带汉字名时乱码的解决方法
- asp.net文件夹读写权限出错的解决方法
- asp.net下CKFinder IE浏览器中上传图片文件时提示“无效文件名或文件夹名称”的解决方法(原创文章)
- asp.net用input控件上传文件时Check错误文件路径的方法
- 分析ASP.NET读取XML文件4种方法
- ASP.NET中常用的文件上传下载方法
- ASP.NET中常用的文件上传下载方法
- ASP.NET中的cookie读写方法
- asp.net 中引用js文件和css文件的方法
- ASP.Net中上传文件的几种方法
- ASP.NET使用包含文件,比如asp中用include的方法