1.写文件

 

1 FileStream fs = new FileStream(@"E:/新建文件夹/sss.txt", FileMode.OpenOrCreate, FileAccess.Write);
2             byte[] buffer = Encoding.UTF8.GetBytes(Txt1);
3             fs.Position = fs.Length;//设置流的位置,防止覆盖,设置书写位置为末尾
4             fs.Write(buffer,0, buffer.Length);
5             fs.Flush();
6             fs.Close();

 

2.读文件

 1          StringBuilder sb = new StringBuilder();
 2             //读取数据文件
 3             using (FileStream fsRead = new FileStream(@"E:/新建文件夹/OriginalData.dat", FileMode.OpenOrCreate, FileAccess.Read))
 4             {
 5                 long otherLength = fsRead.Length;//还没读取的文件长度
 6                 byte[] buffer = new byte[128];//接收文件的字节数组
 7                 int num = 0;//实际读取的字节数
 8                 int readStartPosit = 0;//开始读取的位置
 9                 while (readStartPosit < 256)
10                 {
11                     fsRead.Position = readStartPosit;//设置文件读取的位置
12                     if (otherLength < buffer.Length)//当剩余文件小于最大读取时
13                     {
14                       num=  fsRead.Read(buffer, readStartPosit, Convert.ToInt32(otherLength));
15                     }
16                     else
17                     {
18                       num=  fsRead.Read(buffer, 0, buffer.Length);
19                     }
20                     if (num <= 0) break;
21 
22                     otherLength -= num;
23                     readStartPosit += num;
24                     sb.Append(Encoding.UTF8.GetString(buffer));
25                 }
26             }
27             Txt1 = sb.ToString();

 

posted on 2018-04-12 17:11  逛园子$$$  阅读(187)  评论(0编辑  收藏  举报