不错呦!smile@林凯西,确保“准备文件”中的几个文件都有安装,S...您好,看了您这篇帖子觉得很有帮助。但是有个问题想请...我的修改过了怎么还被恶意注册呢 @jjjjiiii 用PJ快9年了,主要是A...PJ3啊,貌似很少有人用PJ了,现在不是WP就是z...@332347365,我当时接入时错误码没有-10...楼主,ChkValue值应为-103是什么意思呢?...大哥 你最近能看到我发的信息,请跟我联系,我有个制...
FileStream读写文件示例
编辑:dnawo 日期:2009-08-03
复制内容到剪贴板 程序代码
//引用:
//using System.Text;
//using System.IO;
/// <summary>
/// 写文件
/// </summary>
/// <param name="path">文件路径</param>
/// <param name="context">内容</param>
public void WriteFile(string path, string context)
{
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
{
fs.Write(new byte[] { 239, 187, 191 }, 0, 3); //UTF8 BOM:EF BB BF
byte[] info = new UTF8Encoding(true).GetBytes(context);
fs.Write(info, 0, info.Length);
}
}
/// <summary>
/// 读文件
/// </summary>
/// <param name="path">文件路径</param>
/// <returns></returns>
public string ReadFile(string path)
{
StringBuilder sb = new StringBuilder();
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
//用此方法读取后直接写入时,新文件和原文件可能不一致
//byte[] b = new byte[1024];
//UTF8Encoding temp = new UTF8Encoding(true);
//while (fs.Read(b, 0, b.Length) > 0)
//{
// sb.Append(temp.GetString(b));
//}
byte[] b = new byte[fs.Length];
UTF8Encoding temp = new UTF8Encoding(true);
fs.Read(b, 0, b.Length);
sb.Append(temp.GetString(b));
}
return sb.ToString();
}
//using System.Text;
//using System.IO;
/// <summary>
/// 写文件
/// </summary>
/// <param name="path">文件路径</param>
/// <param name="context">内容</param>
public void WriteFile(string path, string context)
{
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
{
fs.Write(new byte[] { 239, 187, 191 }, 0, 3); //UTF8 BOM:EF BB BF
byte[] info = new UTF8Encoding(true).GetBytes(context);
fs.Write(info, 0, info.Length);
}
}
/// <summary>
/// 读文件
/// </summary>
/// <param name="path">文件路径</param>
/// <returns></returns>
public string ReadFile(string path)
{
StringBuilder sb = new StringBuilder();
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
//用此方法读取后直接写入时,新文件和原文件可能不一致
//byte[] b = new byte[1024];
//UTF8Encoding temp = new UTF8Encoding(true);
//while (fs.Read(b, 0, b.Length) > 0)
//{
// sb.Append(temp.GetString(b));
//}
byte[] b = new byte[fs.Length];
UTF8Encoding temp = new UTF8Encoding(true);
fs.Read(b, 0, b.Length);
sb.Append(temp.GetString(b));
}
return sb.ToString();
}
FileStream类主要是操作字节和字节数组,它提供了在文件中读写字节的方法,因而可用它来处理任何数据文件,而不仅仅是文本文件。这种灵活性的代价是,不能使用FileStream类将数据直接读入字符串或将字符串直接写入文件,平时我们更常用StreamWriter和StreamReader来完成文件的读取功能。但是有些操作,比如随机文件访问(访问文件中间某点的数据),还是必须由FileStream对象执行。
评论: 0 | 引用: 0 | 查看次数: 5515
发表评论
请登录后再发表评论!