在我们编写程序的时候经常会用到文件流的操作,这里作为一种便签的方式记录下,方便日后查找。
一.文件流
/* 写文件流 方式1
FileStream fst = new FileStream("test2.txt", FileMode.Append, System.IO.FileAccess.Write);
注意:FileMode.Append 有很多种情况,具体的情况可以在VS20XX里面点击进去查看
*/
string str = "\r\nhello world\r\n";
byte[] bytes1 = new byte[1024];
bytes1 = Encoding.UTF8.GetBytes(str);
FileStream fst = new FileStream("test2.txt", FileMode.Append, System.IO.FileAccess.Write);
fst.Write(bytes1, 0, bytes1.Length);
fst.Close();
MessageBox.Show("OK");
/*写文件流 方式2
FileStream fst = File.OpenWrite("test3.txt");
*/
string str = "\r\nhello world\r\n";
byte[] bytes1 = new byte[1024];
bytes1 = Encoding.UTF8.GetBytes(str);
FileStream fst = File.OpenWrite("test3.txt");
fst.Write(bytes1, 0, bytes1.Length);
fst.Close();
MessageBox.Show("OK");
/*
写文件流 方式3
StreamWriter sw = new StreamWriter("test.txt", false);
StreamWriter sw = File.AppendText("test.txt");
false---覆盖
true ---追加
*/
StreamWriter sw = new StreamWriter("test.txt", false);
sw.WriteLine("您好,魔兽世界");
sw.WriteLine("您好,这个世界");
sw.Flush();
sw.Close();
MessageBox.Show("OK");
/*读文件流 方式1
FileStream fs2 = new FileStream("test.txt", FileMode.OpenOrCreate, System.IO.FileAccess.Read);
*/
FileStream fs2 = new FileStream("test.txt", FileMode.OpenOrCreate, System.IO.FileAccess.Read);
byte[] bytes1 = new byte[1024];
int num=fs2.Read(bytes1, 0, bytes1.Length);
fs2.Close();
MessageBox.Show("num=" + num.ToString());
MessageBox.Show(Encoding.UTF8.GetString(bytes1));
/*读文件流 方式2
FileStream fs = File.OpenRead("test.txt");
*/
FileStream fs = File.OpenRead("test.txt");
byte[] bytes2 = new byte[1024];
int num = fs.Read(bytes2, 0, bytes2.Length);
fs.Close();
MessageBox.Show("num=" + num.ToString());
MessageBox.Show(Encoding.UTF8.GetString(bytes2));
/*
读文件流 方式3
using (StreamReader sr = new StreamReader(@"test.txt", Encoding.UTF8, false))
*/
using (StreamReader sr = new StreamReader(@"test.txt", Encoding.UTF8, false))
{
while (!sr.EndOfStream)
{
Console.WriteLine(sr.ReadLine());
}
}
MessageBox.Show("读取完毕");
Console.Read();
二.内存流读写
byte[] bytes = Encoding.UTF8.GetBytes("hello world");
using (MemoryStream ms = new MemoryStream())
{
ms.Write(bytes, 0, bytes.Length);
byte[] byte2 = new byte[bytes.Length];
ms.Position = 0;//这个地方很重要,否则出错
int n = ms.Read(byte2, 0, byte2.Length);
MessageBox.Show("n=" + n.ToString());
MessageBox.Show(Encoding.UTF8.GetString(byte2));
}