20141104文件流的写入与读取

流:(I/O)
分类:文件流,内存流,网络流。
命名空间:using System.IO;

类:FileStream
构造:
FileStream stream = new FileStream(@"d:\test.txt", FileMode.Create);
FileStream stream = new FileStream(@"d:\test.txt", FileMode.Create, FileAccess.ReadWrite);

属性:
Length:流的长度
Position:流的当前位置

方法:
Write(byte[] 流的内容,int 从第几个位置开始写,int 写入的长度):写文件
Read(byte[] 用来存放读取出来的流的空间,int 从第几个位置开始读,int 读入的长度):读文件
Seek(int 偏移量,SeekOrignal 从哪开计算偏移):调整流的当前位置
Flush():把缓冲区的内容,全写到文件中去。
Close():关闭流。

 

//技巧点:启动外部EXE程序
System.Diagnostics.Process.Start(@"D:\Program Files (x86)\Tencent\QQ\QQProtect\Bin\QQProtect.exe");

eg:

 

 1 /// <summary>
 2 /// 写入操作
 3 /// </summary>
 4 /// <param name="sender"></param>
 5 /// <param name="e"></param>
 6 private void button1_Click(object sender, EventArgs e)
 7 {
 8     FileStream fs = null;
 9     try
10     {
11     //建立文件流对象
12     fs = new FileStream(@"e:\test.txt", FileMode.Create);
13     //把要写的内容转化为二进制数组
14     byte[] bs = System.Text.Encoding.Default.GetBytes(textBox1.Text);
15     //用White()写入
16     fs.Write(bs, 0, bs.Length);
17     }
18     finally
19     {
20 if (fs != null)
21 {
22     //关闭流
23     fs.Close();
24     MessageBox.Show("文件写入成功!");
25 }
26     }
27 }
28 /// <summary>
29 /// 读取操作
30 /// </summary>
31 /// <param name="sender"></param>
32 /// <param name="e"></param>
33 private void button2_Click(object sender, EventArgs e)
34 {
35     FileStream fs = null;
36     try
37     {
38     //建立文件流对象
39     fs = new FileStream(@"e:\test.txt", FileMode.Open);
40     //读取流
41     //造个二进制数组,用来接受取出来的流的数据。
42     byte[] bs = new byte[fs.Length];
43     //使用流的Read()方法,从流中读取二进制数据出来。
44     fs.Read(bs, 0, bs.Length);
45     //使用Encoding.GetString()方法,把二进制数组变成字符串。
46     textBox1.Text = System.Text.Encoding.Default.GetString(bs);
47     }
48     finally
49     {
50 if (fs != null)
51 {
52     fs.Close();
53 }
54     }
55 }

 

posted on 2014-11-04 21:15  格林威治  阅读(154)  评论(0编辑  收藏  举报

友情链接:活动板房 金伟利经贸 淄博月子中心 不锈钢激光切割机 玻璃鳞片胶泥 珍珠棉