c# filestream
类为文件操作提供了一个流。它可以用于执行同步和异步的读写操作。在filestream
类的帮助下,我们可以轻松地将数据读写到文件中。
下面来看看一个使用filestream
类的简单例子,它实现将单字节的数据写入文件。在这里,使用openorcreate
文件模式打开文件,这样的话可以对文件执行读写操作。
using system;
using system.io;
public class filestreamexample
{
public static void main(string[] args)
{
filestream f = new filestream("e:\\filestream-demo.txt", filemode.openorcreate);//creating file stream
f.writebyte(65);//writing byte into stream
f.close();//closing stream
}
}
执行上面代码后,打文件:filestream-demo.txt应该会看到以下内容 -
a
下面再来看看另外一个例子,使用循环将多个字节的数据写入文件。
using system;
using system.io;
public class filestreamexample
{
public static void main(string[] args)
{
filestream f = new filestream("e:\\filestream-demo.txt", filemode.openorcreate);
for (int i = 65; i <= 90; i++)
{
f.writebyte((byte)i);
}
f.close();
}
}
执行上面代码后,打文件:filestream-demo.txt应该会看到以下内容 -
abcdefghijklmnopqrstuvwxyz
下面来看看一个使用filestream
类从文件中读取数据的例子。 这里,filestream
类的readbyte()
方法返回单字节。要读取所有的字节,需要使用循环。
using system;
using system.io;
public class filestreamexample
{
public static void main(string[] args)
{
filestream f = new filestream("e:\\filestream-demo.txt", filemode.openorcreate);
int i = 0;
while ((i = f.readbyte()) != -1)
{
console.write((char)i);
}
f.close();
}
}
执行上面代码后,应该会看到输出以下内容 -
abcdefghijklmnopqrstuvwxyz