一 .NET Framework 类库的System.IO 命名空间
System.IO 命名空间包含允许读写文件和数据流的类型以及提供基本文件和目录支持的类型。
二 C#文件读写之FileStream详解
1. (FileStream fs1 = File.Open("c://test.txt", FileMode.Open));
FileMode.Open 直接用FileStream类打开文件c://test.txt"。
2. (FileStream fs2 = File.Open("c://test.txt", FileMode.Append, FileAccess.Write));
FileMode.Append,以追加的方式打开文件"c://test.txt",将某些内容写到"c://test.txt"里。
3.(FileStream fs3 =File.Open("c://test.txt", FileMode.Truncate, FileAccess.ReadWrite, FileShare.Read)).
FileMode.Truncate的意思是将文件打开清空里面的内容后再对文件进行操作。
4. FileStream MyFileStream1 = new FileStream(@"c:/Testing.txt", FileMode.Create);
这个方法的意思是创建一个可以读写的文件,并且可以允许其他人读取文件的内容。
三 C#基于流的输入输出
C#基于流的输入输出.:Stream-通过C# I/O 系统与物理设备连接起来,也就是平时读写的硬盘等物理存贮设备.流/Stream的方法和属性有:
Method/ Properties 描述
void Close() 关闭流
void Flush() 清理流中的内容
int ReadByte() 返回一个整数表示输入的字节数,如果没有数据返回-1
int Read(byte[ ] buf,int offset, int numBytes) 将numBytes个字节读入到byte[ ]的以offset为,起始位置,返回读入成功的字节数
Long Seek(long offset,SeekOrigin origin) 将当前位置定位到以origin为初始位置以后的offset处.
void WriteByte(byte b) 将单个字节写入到一个输出流.
void Write(byte[ ] buf,int offset, int numBytes) 写入byte[ ] buf中从offset开始的numBytes个字节.
bool CanRead 是否可读
bool CanSeek 是否支持寻址
bool CanWrite 是否可以写入数据
long Length 流的长度
long Position 流的当前位置.
三. 流的继承结构
Stream是一个很大类的,在读写文件的时候,可以通过不同的流进行专业的数据读写.
The FileMode and FileAccess的几条规则:
Value | 意义 |
FileMode.Create | 创建文件,在在同名的文件将被毁掉 |
FileMode.CreateNew | 创建文件,这个文件之前不在在 |
FileMode.Open | 打开已经在在的文件 |
FileMode.OpenOrCreate | 如果文件在在,打开文件,否则,创建新文件 |
FileMode.Truncate | 打开已经存在的文件,将它的内容清除掉 |
FileMode.Append | 以追加的形式将数据写入到文件最后 |
如果在打开文件的时候想限制文件访问权限,那么可以做如下的构造方法:
FileStream(string filename, FileMode mode, FileAccess access);
文件名 文件模式 操作模式
Access可以是以下当中的一个值:
FileAccess.Read/ FileAccess.Write/ FileAccess.ReadWrite;
FileStreamfs=new FileStream(“c://tab.txt”,FileMode.OpenOrCreate,FileAccess.Read);
C#中结合Post发送的Stream与Byte Array的操作似乎资料很少.下面是我这几天的研究成果.功能是将同文件夹下的a.jpg复制生成b.jpg.代码如下:
byteArray.aspx.cs
gopost.aspx.cs
相对来说,byte Array在Html表单中的应用可能一直被忽视,但是正确的应用byte Array可以大大的优化程序,并做出一些意想不到的效果来。
C# Stream 和 byte[] 之间的转换
/* - - - - - - - - - - - - - - - - - - - - - - - -
* Stream 和 byte[] 之间的转换
* - - - - - - - - - - - - - - - - - - - - - - - */
另外,XML的一个应用是序列化,要用到把字符串转化成byte数组,方法:
byte[] bytes = System.Text.UTF8Encoding.UTF8.GetBytes(XmlContent);
相对的,把byte数组转化为字符串的方法则为:
string XmlContent = System.Text.UTFEncoding.UTF8.GetString(bytes);
从字符串到流Stream
byte[] buffer = System.Text.Encoding.Unicode.GetBytes("faint");
MemoryStream stream = new MemoryStream(buffer);
MemoryStream ms = new MemoryStream(System.Text.Encoding.Default.GetBytes(AObjStr));