在项目开发中经常会涉及到对文件的读写,c# 提供了很多种方式来对文件进行读写操作,今天来说说FileStream 对象。
FileStream表示在磁盘或网络路径上指向文件的流。一般操作文件都习惯使用StreamReader 和 StreamWriter,因为它们操作的是字符数据 。而FileStream 对象操作的是字节和字节数组。有些操作是必须使用FileStream 对象执行的,如随机访问文件中间某点的数据。
创建FileStream 对象有许多不同的方法,这里使用文件名和FileMode枚举值创建:
一、 读取文件,记得引用 System.IO 命名空间:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
using System; using System.Collections.Generic; using System.Text; using System.IO; namespace ConsoleApplicationTest { class Program { static void Main( string [] args) { //创建需要读取的数据的字节数组和字符数组 byte [] byteData = new byte [200]; char [] charData = new char [200]; //捕获异常:操作文件时容易出现异常,最好加上try catch FileStream file = null ; try { //打开一个当前 Program.cs 文件,此时读写文件的指针(或者说操作的光标)指向文件开头 file = new FileStream( @"..\..\Program.cs" , FileMode.Open); //读写指针从开头往后移动10个字节 file.Seek(10, SeekOrigin.Begin); //从当前读写指针的位置往后读取200个字节的数据到字节数组中 file.Read(byteData, 0, 200); } catch (Exception e) { Console.WriteLine( "读取文件异常:{0}" ,e); } finally { //关闭文件流 if (file != null ) file.Close(); } //创建一个编码转换器 解码器 Decoder decoder = Encoding.UTF8.GetDecoder(); //将字节数组转换为字符数组 decoder.GetChars(byteData, 0, 200, charData, 0); Console.WriteLine(charData); Console.ReadKey(); } } } |
显示结果如下:
二、写入文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
using System; using System.Collections.Generic; using System.Text; using System.IO; namespace ConsoleApplicationTest { class Program { static void Main( string [] args) { byte [] byteData; char [] charData; FileStream file = null ; try { //在当前启动目录下的创建 aa.txt 文件 file = new FileStream( "aa.txt" , FileMode.Create); //将“test write text to file”转换为字符数组并放入到 charData 中 charData = "Test write text to file" .ToCharArray(); byteData = new byte [charData.Length]; //创建一个编码器,将字符转换为字节 Encoder encoder = Encoding.UTF8.GetEncoder(); encoder.GetBytes(charData, 0, charData.Length, byteData, 0, true ); file.Seek(0, SeekOrigin.Begin); //写入数据到文件中 file.Write(byteData, 0, byteData.Length); } catch (Exception e) { Console.WriteLine( "写入文件异常:{0}" ,e); } finally { if (file != null ) file.Close(); } Console.ReadKey(); } } } |
结果如下:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://www.cnblogs.com/lhgohead/p/6172159.html