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 }

 

转载于:https://www.cnblogs.com/zsmj001/p/4073103.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值