20110224C#程序员参考手册
Stream类是所有字节流的基类,它定义了用来读写字节数据的基本方法。
/* * BufferedStream:类为其他的I/O流动读和写提供了一个内部的缓冲区, * 一个缓冲区就是用来临时存储数据的一块内存,在把数据从文件读出或者把数据写入文件时, * 读写的数据已经实现了缓冲。 * FileStream:能够访问文件I/O流,它允许文件的读取或者写入 */ int c; StringBuilder sb = new StringBuilder(); BufferedStream buffered = new BufferedStream(new FileStream(@"F:\demo.txt", FileMode.Open)); while ((c = buffered.ReadByte()) != -1) { sb.Append((char)c); } Console.WriteLine(sb.ToString()); buffered.Close();
using System; using System.IO; using System.Text; class Test { public static void Main() { string path = @"c:\temp\MyTest.txt"; // Delete the file if it exists. if (File.Exists(path)) { File.Delete(path); } //Create the file. using (FileStream fs = File.Create(path)) { AddText(fs, "This is some text"); AddText(fs, "This is some more text,"); AddText(fs, "\r\nand this is on a new line"); AddText(fs, "\r\n\r\nThe following is a subset of characters:\r\n"); for (int i=1;i < 120;i++) { AddText(fs, Convert.ToChar(i).ToString()); } } //Open the stream and read it back. using (FileStream fs = File.OpenRead(path)) { byte[] b = new byte[1024]; UTF8Encoding temp = new UTF8Encoding(true); while (fs.Read(b,0,b.Length) > 0) { Console.WriteLine(temp.GetString(b)); } } } private static void AddText(FileStream fs, string value) { byte[] info = new UTF8Encoding(true).GetBytes(value); fs.Write(info, 0, info.Length); } }
打开一个文件(如果文件不存在则创建该文件)并将信息追加到文件末尾。
using System; using System.IO; using System.Text; class FSOpenWrite { public static void Main() { FileStream fs=new FileStream("c:\\Variables.txt", FileMode.Append, FileAccess.Write, FileShare.Write); fs.Close(); StreamWriter sw=new StreamWriter("c:\\Variables.txt", true, Encoding.ASCII); string NextLine="This is the appended line."; sw.Write(NextLine); sw.Close(); } }
说明:代码选自http://msdn.microsoft.com/zh-cn/library/system.io.filestream.aspx

浙公网安备 33010602011771号