Code
1using System;
2using System.IO;
3class MyStream
4{
5 private const string FILE_NAME = "Test.data"; //定义文件名
6 public static void Main(String[] args)
7 {
8 // 检查是否文件已经存在
9 if (File.Exists(FILE_NAME))
10 {
11 Console.WriteLine("{0} already exists!", FILE_NAME);
12 return;
13 }
14 FileStream fs = new FileStream(FILE_NAME, FileMode.CreateNew);
15 // 建立读写流
16 BinaryWriter w = new BinaryWriter(fs);
17 // 写入测试数据
18 for (int i = 0; i < 11; i++)
19 {
20 w.Write( (int) i);
21 }
22 w.Close();
23 fs.Close();
24 //建立读取类.
25 fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
26 BinaryReader r = new BinaryReader(fs);
27
28
29 // 读取测试数据
30
31 for (int i = 0; i < 11; i++)
32 {
33 Console.WriteLine(r.ReadInt32());
34 }
35 r.Close();
36 fs.Close();
37 }
38}
39
40
1using System;
2using System.IO;
3class MyStream
4{
5 private const string FILE_NAME = "Test.data"; //定义文件名
6 public static void Main(String[] args)
7 {
8 // 检查是否文件已经存在
9 if (File.Exists(FILE_NAME))
10 {
11 Console.WriteLine("{0} already exists!", FILE_NAME);
12 return;
13 }
14 FileStream fs = new FileStream(FILE_NAME, FileMode.CreateNew);
15 // 建立读写流
16 BinaryWriter w = new BinaryWriter(fs);
17 // 写入测试数据
18 for (int i = 0; i < 11; i++)
19 {
20 w.Write( (int) i);
21 }
22 w.Close();
23 fs.Close();
24 //建立读取类.
25 fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
26 BinaryReader r = new BinaryReader(fs);
27
28
29 // 读取测试数据
30
31 for (int i = 0; i < 11; i++)
32 {
33 Console.WriteLine(r.ReadInt32());
34 }
35 r.Close();
36 fs.Close();
37 }
38}
39
40
上面的代码示例演示如何向新的空文件流 (Test.data
) 写入数据及从中读取数据。