StreamReader 与 FileStream 的区别用法 (有关StreamReader的内容参考http://blog.sina.com.cn/s/blog_796ffec50100te51.html)
StreamReader 旨在以一种特定的编码输出字符,而 Stream 类用于字节的输入和输出。
使用 StreamReader 读取标准文本文件的各行信息。可以按照指定的编码集来读取,读取文本功能比较强大而FileStream 的文件读取效率较高,读取字节流比较方便
FileStream的用法
1.读入操作
在读入button按钮中添加代码:
FileStream fileStream = new FileStream(@"..\??.text",FileMode.Open);
StreamReader sr = new StreamReader(fileStream,Encoding.GetEncoding("gb2312"),true);
textBox1.Text = sr.ReadToEnd() + "\n";
fileStream.Close();
其中,涉及到解码问题,在这里,encode一定要设定为“gb2312”,gb2312是中文编码格式,如果不这样设定,会产生接收乱码问题。
2.复制文件
private void button3_Click(object sender, EventArgs e)
{
CopyFile(@"E:\91卫图助手\玩一玩别当真\玩一玩别当真.txt", @"E:\91卫图助手\玩一玩别当真\玩一玩别当真1.txt");
FileStream fileStream = new FileStream(@"E:\91卫图助手\玩一玩别当真\玩一玩别当真1.txt", FileMode.Open);
StreamReader sr = new StreamReader(fileStream, Encoding.GetEncoding("gb2312"), true);
textBox1.Text = sr.ReadToEnd() + "\n";
fileStream.Close();
}
static void CopyFile(string inName, string toName)
{
using (FileStream inStream = File.OpenRead(inName))//使用using可以自动释放资源
{
using (FileStream toStream = File.OpenWrite(toName))
{
CopyStream(inStream, toStream, 1);//bufferSize = 1,只要>0的值,就能读到所有的值
}
}
}
static void CopyStream(Stream inStream, Stream toStream,int bufferSize)
{
byte[] buffer = new byte[bufferSize];
int n;
while((n=inStream.Read(buffer,0,bufferSize))>0)
{
//向toStream流中写入字节系列
toStream.Write(buffer, 0, n);
//获取inStream流位置,让toStream流的位置和它保持一致
toStream.Position = inStream.Position;
}
}
3.创建文件并写入文件
private void button2_Click(object sender, EventArgs e)
{
using (FileStream fs = File.Create(@"E:\91卫图助手\玩一玩别当真\玩一玩别当真2.txt"))
{
string strCopy = "";
strCopy = textBox1.Text;
byte[] buffer = Encoding.UTF8.GetBytes(strCopy);
fs.Write(buffer, 0, buffer.Length);
fs.Flush();
}
}