看代码,注解在代码中
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
namespace DataRowDemo
{
class Program
{
static void Main(string[] args)
{
#region FileStream Read
byte[] byDate = new byte[10000];
char[] chDate = new char[10000];
try
{
//创建文件流,打开已有的文件 Program.cs (当前目录的上上层) FileStream 只能操作字节
FileStream fs = new FileStream(@"..\..\Program.cs", FileMode.Open);
fs.Seek(135, SeekOrigin.Begin); //将文件指针移动到 文件开头后 135 个子杰后
fs.Read(byDate,0,200); // 将接下来的200个字节读入到byDate数组中 0表示从第0个位置开始存储内容
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
//将字节数组转化为 字符数组
Decoder d = Encoding.UTF8.GetDecoder();
d.GetChars(byDate, 0, byDate.Length, chDate, 0);
Console.WriteLine(chDate);
Console.Read();
#endregion
#region StreamReader 对象
StreamReader sr = new StreamReader(@"..\..\Program.cs"); //创建streamreader 的一种方式,另一种见下面的
string stLine = sr.ReadLine(); //从当前;流中读取一行字符串返回
while (stLine != null)
{
Console.WriteLine(stLine);
stLine = sr.ReadLine();
}
sr.Close();
#endregion
#region StreamWriter 对象 (允许将字符和字符串写入文件 如果不需要改变文件指针位置,很容易操作文件)
try
{
FileStream fs = new FileStream("Log.txt", FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(fs); //StreamWriter的创建方式
sw.WriteLine("hahah1");
sw.WriteLine("haha2");
sw.Close();
}
catch (Exception)
{
throw;
}
#endregion
#region FileStream Write
byte[] byDate;
char[] charDate;
try
{
FileStream fs = new FileStream("Temp.txt", FileMode.Create);
charDate = "hello ,this is my pracetice demo".ToCharArray();
//将字符串数组转化成FileStream对象需要的字节数组
byDate = new byte[charDate.Length];
Encoder e = Encoding.UTF8.GetEncoder();
e.GetBytes(charDate, 0, charDate.Length, byDate, 0, true);
fs.Seek(0, SeekOrigin.Begin); //将指针移动到0 个位置
fs.Write(byDate, 0, byDate.Length); //将byDate写入到文件中 三个参数分别表示要写入的数组,写入数组的下表 和写入的长度
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
#endregion
}
}
}