Stream
程序员文章站
2022-05-27 22:58:20
...
流涉及三个基本操作:
-
读取 - 将数据从流传输到数据结构(如字节数组)中。
-
写入 - 将数据从数据源传输到流。
-
查找 - 对流中的当前位置进行查询和修改
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); } //创建一个文件,向流里面写数据 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()); } } //打开一个文件流,读取流里面的数据 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); } }