C# System.IO 文件流输入输出

一、读写文本文件

可以用fileStream来读写文本文件,但是FileStream是通过字节形式来读写数据的,要把字节数据转换为文本,要自己处理编码转换。

对于文本文件的读写,通常用 StreamReader类和 StreamWriter类更方便。其底层是通过FileStream实现读写文本文件的。

 

1、构造函数

 

Public StreamReader(string path,Encoding encodeing)

其中path指定要读取的完整文件路径,encoding指定要使用的字节编码。例如GB2312,UTF8等编码形式

 

 

using System;
using System.IO;
using System.Text;

namespace StreamReader
{
	class Program
	{
		[STAThread]
		public static void Main(string[] args)
		{
			StreamReader sr=new StreamReader("f:\\temp.txt",Encoding.GetEncoding("gb2312"));
			string line;
			while((line=sr.ReadLine())!=null)
			{
				Console.WriteLine(line);
			}
			sr.close();
		}
	}
}

 

 

 

 

 

二、写入文本文件

与StreamReader类对应的类是StreamWriter类,它专门用于写入文本文件

1、构造函数

Public StreamWrite(string path,bool append,Encoding encoding);

其中path指定要写入的完整文件路径,append为false则该文件被改写,如果该文件存在,并且append为true,则数据被追加到该文件中。否则将创建新文件。Encoding指定要使用的字节编码。

 

(注意:append为true为追加,append为false为覆盖)

 

using System;
using System.IO;
using System.Text;

namespace StreamReader
{
	class Program
	{
		[STAThread]
		public static void Main(string[] args)
		{
			StreamWriter sw=new StreamWriter("f:\\temp.txt",true,Encoding.GetEncoding("gb2312"));
			string line="hello world!;
				sw.WriteLine(line);
			sw.close();
		}
	}
}


三、Stream类

 

是派生出各种类的抽象类,处理字节流

其中一些派生类包括

– FileStream

– MemoryStream

– BufferedStream

– CryptoStream

方法包括:

 

3.1FileStream类构造函数

FileStream(string FilePath, FileMode)

FileStream(string FilePath, FileMode, FileAccess)

FileStream(string FilePath, FileMode, FileAccess, FileShare)

方法:

int Read(byte array, offset, count)

int ReadByte( )

void Write(byte array, offset, count)

void WriteByte(byte value)

 

枚举数:

FileMode 枚举数

– Append

– Create

/若文件已存在,则引发IO异常

– CreateNew

– Open

– OpenOrCreate

– Truncate

FileAccess 枚举数

– Read

– Write

– ReadWrite

FileShare 枚举数

– None

– Read

– Write

– ReadWrite

 

3.2MemoryStream类

用于从内存中读取数据和将数据写入内存中

以下是 MemoryStream 的一些方法

 

int Read(byte array, offset, count)

int ReadByte( )

void Write(byte array, offset, count)

void WriteByte(byte value)

void WriteTo(Stream stream)

 

3.3BufferedStream类

用于在缓冲区中读取和写入

• 当缓冲区满(默认缓冲区大小:4096 字节)或关闭时,内容将自动刷新输出到底层流

它有两个重载的构造函数

Public BufferedStream(Stream StName);

Public BufferedStream(Stream StName,int bsize);

 

3.4CryptoStream

对数据流中的数据进行加密、解密

using System.Security.Cryptography;

使用前加上上面的命名空间

 

四、Dirctory类

 

1.Directory类

目录使用 Directory类,可以用目录类创建、移动目录,并可列举目录及子目录的内容。Directory类全部是静态方法。

 

2、DirectoryInfo类

在使用DirectoryInfo类的属性和方法前必须先创建它的对象实例,在创建时需要指定该实例所对应的目录。例如:DirectoryInfo di=new DirectoryInfo(''c:\\mydir'');DirectoryInfo类的常用方法见表。

 

五、Path类

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值