为文件提供 Stream,既支持同步读写操作,也支持异步读写操作。
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=;i < ;i++)
{
AddText(fs, Convert.ToChar(i).ToString()); }
} //Open the stream and read it back.
using (FileStream fs = File.OpenRead(path))
{
byte[] b = new byte[];
UTF8Encoding temp = new UTF8Encoding(true);
while (fs.Read(b,,b.Length) > )
{
Console.WriteLine(temp.GetString(b));
}
}
} private static void AddText(FileStream fs, string value)
{
byte[] info = new UTF8Encoding(true).GetBytes(value);
fs.Write(info, , info.Length);
}
}
构造函数
属性
CanRead |
获取一个值,该值指示当前流是否支持读取。 |
CanSeek |
获取一个值,该值指示当前流是否支持查找。 |
CanTimeout |
获取一个值,该值确定当前流是否可以超时。 (Inherited from Stream) |
CanWrite |
获取一个值,该值指示当前流是否支持写入。 |
Handle |
获取当前 |
IsAsync |
获取一个值,它指示 |
Length |
获取用字节表示的流长度。 |
Name |
获取 |
Position |
获取或设置此流的当前位置。 |
ReadTimeout |
获取或设置一个值(以毫秒为单位),该值确定流在超时前尝试读取多长时间。 (Inherited from Stream) |
SafeFileHandle |
获取 SafeFileHandle 对象,它代表当前 FileStream 对象所封装的文件的操作系统文件句柄。 |
WriteTimeout |
获取或设置一个值(以毫秒为单位),该值确定流在超时前尝试写入多长时间。 (Inherited from Stream) |
方法
IDisposable.Dispose() |
释放由 Stream 使用的所有资源。 (Inherited from Stream) |