中英文外贸网站建设,网站制作公司官网,苏州网页制作设计,能免费做婚礼邀请函的网站1. 文件流的基本概念 文件流是C#中处理文件读写的抽象#xff0c;它提供了对文件内容进行顺序访问的能力。在文件流中#xff0c;数据按照字节或块的方式传输#xff0c;而不受文件中数据的格式影响。文件流通常与System.IO命名空间中的类一起使用#xff0c;包括FileStrea…1. 文件流的基本概念 文件流是C#中处理文件读写的抽象它提供了对文件内容进行顺序访问的能力。在文件流中数据按照字节或块的方式传输而不受文件中数据的格式影响。文件流通常与System.IO命名空间中的类一起使用包括FileStream、StreamReader和StreamWriter等。 2、使用FileStream类创建一个文件并写入数据
using System;
using System.IO;class Program
{static void Main(){string path C:\Temp\MyTest.txt;// 使用FileMode.Create创建新文件或者覆盖已有的文件using (FileStream fs new FileStream(path, FileMode.Create)){byte[] data System.Text.Encoding.UTF8.GetBytes(This is some text);// 写入数据到文件fs.Write(data, 0, data.Length);}}
} 3、读取文件流中的数据
using System;
using System.IO;class Program
{static void Main(){string path C:\Temp\MyTest.txt;// 使用FileMode.Open打开已有的文件using (FileStream fs new FileStream(path, FileMode.Open)){byte[] data new byte[1024];int byteRead fs.Read(data, 0, data.Length);// 转换为字符串并显示Console.WriteLine(System.Text.Encoding.UTF8.GetString(data, 0, byteRead));}}
} 4、使用StreamReader和StreamWriter来读写文本文件 using System;
using System.IO;class Program
{static void Main(){string path C:\Temp\MyTest.bin;// 使用BinaryWriter写入二进制数据using (BinaryWriter bw new BinaryWriter(File.Open(path, FileMode.Create))){bw.Write(Hello World!);}// 使用BinaryReader读取二进制数据using (BinaryReader br new BinaryReader(File.Open(path, FileMode.Open))){string result br.ReadString();Console.WriteLine(result);}}
}
以上就是一些使用C#文件流的基本方法。在实际应用中你可能需要根据具体需求来选择合适的类和方法来处理文件流。