👉本文关键字:System.IO、BufferedStream类、方法示例、C#
文章目录
- 1️⃣ System.IO命名空间
- 2️⃣ BufferedStream类
- ♈ 定义
- ♉ 示例
- ♉ 构造函数
- ♊ 属性
- ♌ 常用方法
- Close() 关闭当前流并释放与之关联的所有资源(如套接字和文件句柄)
- CopyTo(Stream) 从当前流中读取字节并将其写入到另一流中
- CopyTo(Stream, Int32) 使用指定的缓冲区大小,从当前流中读取字节并将其写入到另一流中
- CopyToAsync(Stream) 从当前流中异步读取字节并将其写入到另一个流中
- Dispose() 释放由 Stream 使用的所有资源
- Read(Byte[], Int32, Int32) 将字节从当前缓冲流复制到数组
- ReadAsync(Byte[], Int32, Int32) 从当前流异步读取字节序列,并将流中的位置提升读取的字节数
- ReadByte() 从基础流中读取一个字节,并返回转换为 `int` 的该字节;或者如果从流的末尾读取则返回 -1
- Write(Byte[], Int32, Int32) 将字节复制到缓冲流,并将缓冲流内的当前位置前进写入的字节数
- WriteAsync(Byte[], Int32, Int32) 将字节序列异步写入当前流,并将流的当前位置提升写入的字节数
- WriteByte(Byte) 一个字节写入文件流中的当前位置
- Flush() 清除此流的缓冲区,使得所有缓冲数据都写入到文件中
- FlushAsync() 异步清除此流的所有缓冲区并导致所有缓冲数据都写入基础设备中
- ♍ 注解
- ♎ 更多方法
1️⃣ System.IO命名空间
.NET中的IO操作命名空间,包含允许读写文件和数据流的类型以及提供基本文件和目录支持的类型。
我们在.NET中的IO操作,经常需要调用一下几个类。
- FileStream类
文件流类,负责大文件的拷贝,读写。
- Path类
Path类中方法,基本都是对字符串(文件名)的操作,与实际文件没多大关系。
-
File类
File类可以进行一些对小文件拷贝、剪切操作,还能读一些文档文件。
-
Dirctory类
目录操作,创建文件、删除目录,获取目录下文件名等等。
2️⃣ BufferedStream类
♈ 定义
将缓冲层添加到另一个流上的读取和写入操作。 此类不能被继承。
public sealed class BufferedStream : System.IO.Stream
♉ 示例
下面的代码示例演示如何使用 BufferedStream
类来 NetworkStream
增加某些 I/O 操作的性能。 在启动客户端之前,"开始"菜单远程计算机上的服务器。 启动客户端时,将远程计算机名称指定为命令行参数。 dataArraySize
更改常streamBufferSize
量以查看它们对性能的影响。
第一个示例演示在客户端上运行的代码,第二个示例显示服务器上运行的代码。
示例 1:在客户端上运行的代码
using System;
using System.IO;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
public class Client
{
const int dataArraySize = 100;
const int streamBufferSize = 1000;
const int numberOfLoops = 10000;
static void Main(string[] args)
{
// Check that an argument was specified when the
// program was invoked.
if(args.Length == 0)
{
Console.WriteLine("Error: The name of the host computer" +
" must be specified when the program is invoked.");
return;
}
string remoteName = args[0];
// Create the underlying socket and connect to the server.
Socket clientSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
clientSocket.Connect(new IPEndPoint(
Dns.Resolve(remoteName).AddressList[0], 1800));
Console.WriteLine("Client is connected.\n");
// Create a NetworkStream that owns clientSocket and
// then create a BufferedStream on top of the NetworkStream.
// Both streams are disposed when execution exits the
// using statement.
using(Stream
netStream = new NetworkStream(clientSocket, true),
bufStream =
new BufferedStream(netStream, streamBufferSize))
{
// Check whether the underlying stream supports seeking.
Console.WriteLine("NetworkStream {0} seeking.\n",
bufStream.CanSeek ? "supports" : "does not support");
// Send and receive data.
if(bufStream.CanWrite)
{
SendData(netStream, bufStream);
}
if(bufStream.CanRead)
{
ReceiveData(netStream, bufStream);
}
// When bufStream is closed, netStream is in turn
// closed, which in turn shuts down the connection
// and closes clientSocket.
Console.WriteLine("\nShutting down the connection.");
bufStream.Close();
}
}
static void SendData(Stream netStream, Stream bufStream)
{
DateTime startTime;
double networkTime, bufferedTime;
// Create random data to send to the server.
byte[] dataToSend = new byte[dataArraySize];
new Random().NextBytes(dataToSend);
// Send the data using the NetworkStream.
Console.WriteLine("Sending data using NetworkStream.");
startTime = DateTime.Now;
for(int i = 0; i < numberOfLoops; i++)
{
netStream.Write(dataToSend, 0, dataToSend.Length);
}
networkTime = (DateTime.Now - startTime).TotalSeconds;
Console.WriteLine("{0} bytes sent in {1} seconds.\n",
numberOfLoops * dataToSend.Length,
networkTime.ToString("F1"));
// Send the data using the BufferedStream.
Console.WriteLine("Sending data using BufferedStream.");
startTime = DateTime.Now;
for(int i = 0; i < numberOfLoops; i++)
{
bufStream.Write(dataToSend, 0, dataToSend.Length);
}
bufStream.Flush();
bufferedTime = (DateTime.Now - startTime).TotalSeconds;
Console.WriteLine("{0} bytes sent in {1} seconds.\n",
numberOfLoops * dataToSend.Length,
bufferedTime.ToString("F1"));
// Print the ratio of write times.
Console.WriteLine("Sending data using the buffered " +
"network stream was {0} {1} than using the network " +
"stream alone.\n",
(networkTime/bufferedTime).ToString("P0"),
bufferedTime < networkTime ? "faster" : "slower");
}
static void ReceiveData(Stream netStream, Stream bufStream)
{
DateTime startTime;
double networkTime, bufferedTime = 0;
int bytesReceived = 0;
byte[] receivedData = new byte[dataArraySize];
// Receive data using the NetworkStream.
Console.WriteLine("Receiving data using NetworkStream.");
startTime = DateTime.Now;
while(bytesReceived < numberOfLoops * receivedData.Length)
{
bytesReceived += netStream.Read(
receivedData, 0, receivedData.Length);
}
networkTime = (DateTime.Now - startTime).TotalSeconds;
Console.WriteLine("{0} bytes received in {1} seconds.\n",
bytesReceived.ToString(),
networkTime.ToString("F1"));
// Receive data using the BufferedStream.
Console.WriteLine("Receiving data using BufferedStream.");
bytesReceived = 0;
startTime = DateTime.Now;
int numBytesToRead = receivedData.Length;
while (numBytesToRead > 0)
{
// Read may return anything from 0 to numBytesToRead.
int n = bufStream.Read(receivedData,0, receivedData.Length);
// The end of the file is reached.
if (n == 0)
break;
bytesReceived += n;
numBytesToRead -= n;
}
bufferedTime = (DateTime.Now - startTime).TotalSeconds;
Console.WriteLine("{0} bytes received in {1} seconds.\n",
bytesReceived.ToString(),
bufferedTime.ToString("F1"));
// Print the ratio of read times.
Console.WriteLine("Receiving data using the buffered network" +
" stream was {0} {1} than using the network stream alone.",
(networkTime/bufferedTime).ToString("P0"),
bufferedTime < networkTime ? "faster" : "slower");
}
}
示例 2:在服务器上运行的代码
using System;
using System.Net;
using System.Net.Sockets;
public class Server
{
static void Main()
{
// This is a Windows Sockets 2 error code.
const int WSAETIMEDOUT = 10060;
Socket serverSocket;
int bytesReceived, totalReceived = 0;
byte[] receivedData = new byte[2000000];
// Create random data to send to the client.
byte[] dataToSend = new byte[2000000];
new Random().NextBytes(dataToSend);
IPAddress ipAddress =
Dns.Resolve(Dns.GetHostName()).AddressList[0];
IPEndPoint ipEndpoint = new IPEndPoint(ipAddress, 1800);
// Create a socket and listen for incoming connections.
using(Socket listenSocket = new Socket(
AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp))
{
listenSocket.Bind(ipEndpoint);
listenSocket.Listen(1);
// Accept a connection and create a socket to handle it.
serverSocket = listenSocket.Accept();
Console.WriteLine("Server is connected.\n");
}
try
{
// Send data to the client.
Console.Write("Sending data ... ");
int bytesSent = serverSocket.Send(
dataToSend, 0, dataToSend.Length, SocketFlags.None);
Console.WriteLine("{0} bytes sent.\n",
bytesSent.ToString());
// Set the timeout for receiving data to 2 seconds.
serverSocket.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout, 2000);
// Receive data from the client.
Console.Write("Receiving data ... ");
try
{
do
{
bytesReceived = serverSocket.Receive(receivedData,
0, receivedData.Length, SocketFlags.None);
totalReceived += bytesReceived;
}
while(bytesReceived != 0);
}
catch(SocketException e)
{
if(e.ErrorCode == WSAETIMEDOUT)
{
// Data was not received within the given time.
// Assume that the transmission has ended.
}
else
{
Console.WriteLine("{0}: {1}\n",
e.GetType().Name, e.Message);
}
}
finally
{
Console.WriteLine("{0} bytes received.\n",
totalReceived.ToString());
}
}
finally
{
serverSocket.Shutdown(SocketShutdown.Both);
Console.WriteLine("Connection shut down.");
serverSocket.Close();
}
}
}
♉ 构造函数
BufferedStream(Stream) 使用默认的缓冲区大小 4096 字节初始化 BufferedStream 类的新实例
public BufferedStream (System.IO.Stream stream);
参数
BufferedStream(Stream, Int32) 使用指定的缓冲区大小初始化 BufferedStream 类的新实例
public BufferedStream (System.IO.Stream stream, int bufferSize);
参数
示例
此代码示例是为 BufferedStream 类提供的一个更大示例的一部分。
// Create a NetworkStream that owns clientSocket and
// then create a BufferedStream on top of the NetworkStream.
// Both streams are disposed when execution exits the
// using statement.
using(Stream
netStream = new NetworkStream(clientSocket, true),
bufStream =
new BufferedStream(netStream, streamBufferSize))
♊ 属性
BufferSize 获取此缓冲流的缓冲区大小(以字节为单位)
public int BufferSize { get; }
CanRead 获取一个值,该值指示当前流是否支持读取
public override bool CanRead { get; }
示例
此代码示例是为 BufferedStream 类提供的一个更大示例的一部分。
if(bufStream.CanRead)
{
ReceiveData(netStream, bufStream);
}
CanWrite 获取一个值,该值指示当前流是否支持写入
public override bool CanWrite { get; }
示例
此代码示例是为 BufferedStream 类提供的一个更大示例的一部分。
if(bufStream.CanWrite)
{
SendData(netStream, bufStream);
}
Length 获取流长度,长度以字节为单位
public override long Length { get; }
♌ 常用方法
Close() 关闭当前流并释放与之关联的所有资源(如套接字和文件句柄)
public virtual void Close ();
CopyTo(Stream) 从当前流中读取字节并将其写入到另一流中
public void CopyTo (System.IO.Stream destination);
参数
示例
下面的示例将的内容复制 FileStream 到 MemoryStream 中。
// Create the streams.
MemoryStream destination = new MemoryStream();
using (FileStream source = File.Open(@"c:\temp\data.dat",
FileMode.Open))
{
Console.WriteLine("Source length: {0}", source.Length.ToString());
// Copy source to destination.
source.CopyTo(destination);
}
Console.WriteLine("Destination length: {0}", destination.Length.ToString());
CopyTo(Stream, Int32) 使用指定的缓冲区大小,从当前流中读取字节并将其写入到另一流中
public virtual void CopyTo (System.IO.Stream destination, int bufferSize);
参数
CopyToAsync(Stream) 从当前流中异步读取字节并将其写入到另一个流中
public System.Threading.Tasks.Task CopyToAsync (System.IO.Stream destination);
参数
示例
下面的示例演示如何使用两个 FileStream 对象将文件从一个目录异步复制到另一个目录。 FileStream 类是从 Stream 类派生的。 请注意, Click 控件的事件处理程序 Button 使用修饰符标记, async
因为它调用异步方法
using System;
using System.Threading.Tasks;
using System.Windows;
using System.IO;
namespace WpfApplication
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
string StartDirectory = @"c:\Users\exampleuser\start";
string EndDirectory = @"c:\Users\exampleuser\end";
foreach (string filename in Directory.EnumerateFiles(StartDirectory))
{
using (FileStream SourceStream = File.Open(filename, FileMode.Open))
{
using (FileStream DestinationStream = File.Create(EndDirectory + filename.Substring(filename.LastIndexOf('\\'))))
{
await SourceStream.CopyToAsync(DestinationStream);
}
}
}
}
}
}
Dispose() 释放由 Stream 使用的所有资源
public void Dispose ();
Read(Byte[], Int32, Int32) 将字节从当前缓冲流复制到数组
public override int Read (byte[] buffer, int offset, int count);
参数
返回
示例
此代码示例是为 BufferedStream 类提供的一个更大示例的一部分。
// Receive data using the BufferedStream.
Console.WriteLine("Receiving data using BufferedStream.");
bytesReceived = 0;
startTime = DateTime.Now;
int numBytesToRead = receivedData.Length;
while (numBytesToRead > 0)
{
// Read may return anything from 0 to numBytesToRead.
int n = bufStream.Read(receivedData,0, receivedData.Length);
// The end of the file is reached.
if (n == 0)
break;
bytesReceived += n;
numBytesToRead -= n;
}
bufferedTime = (DateTime.Now - startTime).TotalSeconds;
Console.WriteLine("{0} bytes received in {1} seconds.\n",
bytesReceived.ToString(),
bufferedTime.ToString("F1"));
ReadAsync(Byte[], Int32, Int32) 从当前流异步读取字节序列,并将流中的位置提升读取的字节数
public System.Threading.Tasks.Task<int> ReadAsync (byte[] buffer, int offset, int count);
参数
返回
示例
下面的示例演示如何以异步方式从文件读取。 该示例使用 FileStream 类,该类派生自 Stream 类。
using System;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.IO;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
string filename = @"c:\Temp\userinputlog.txt";
byte[] result;
using (FileStream SourceStream = File.Open(filename, FileMode.Open))
{
result = new byte[SourceStream.Length];
await SourceStream.ReadAsync(result, 0, (int)SourceStream.Length);
}
UserInput.Text = System.Text.Encoding.ASCII.GetString(result);
}
}
}
ReadByte() 从基础流中读取一个字节,并返回转换为 int
的该字节;或者如果从流的末尾读取则返回 -1
public override int ReadByte ();
返回
Write(Byte[], Int32, Int32) 将字节复制到缓冲流,并将缓冲流内的当前位置前进写入的字节数
public override void Write (byte[] buffer, int offset, int count);
参数
示例
此代码示例是为 BufferedStream 类提供的一个更大示例的一部分。
// Send the data using the BufferedStream.
Console.WriteLine("Sending data using BufferedStream.");
startTime = DateTime.Now;
for(int i = 0; i < numberOfLoops; i++)
{
bufStream.Write(dataToSend, 0, dataToSend.Length);
}
bufStream.Flush();
bufferedTime = (DateTime.Now - startTime).TotalSeconds;
Console.WriteLine("{0} bytes sent in {1} seconds.\n",
numberOfLoops * dataToSend.Length,
bufferedTime.ToString("F1"));
WriteAsync(Byte[], Int32, Int32) 将字节序列异步写入当前流,并将流的当前位置提升写入的字节数
public System.Threading.Tasks.Task WriteAsync (byte[] buffer, int offset, int count);
参数
返回
示例
下面的示例演示如何异步写入文件。 该示例使用 FileStream 类,该类派生自 Stream 类。
using System;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.IO;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
UnicodeEncoding uniencoding = new UnicodeEncoding();
string filename = @"c:\Users\exampleuser\Documents\userinputlog.txt";
byte[] result = uniencoding.GetBytes(UserInput.Text);
using (FileStream SourceStream = File.Open(filename, FileMode.OpenOrCreate))
{
SourceStream.Seek(0, SeekOrigin.End);
await SourceStream.WriteAsync(result, 0, result.Length);
}
}
}
}
WriteByte(Byte) 一个字节写入文件流中的当前位置
public override void WriteByte (byte value);
参数
Flush() 清除此流的缓冲区,使得所有缓冲数据都写入到文件中
public override void Flush ();
示例
此代码示例是为 BufferedStream 类提供的一个更大示例的一部分。
// Send the data using the BufferedStream.
Console.WriteLine("Sending data using BufferedStream.");
startTime = DateTime.Now;
for(int i = 0; i < numberOfLoops; i++)
{
bufStream.Write(dataToSend, 0, dataToSend.Length);
}
bufStream.Flush();
bufferedTime = (DateTime.Now - startTime).TotalSeconds;
Console.WriteLine("{0} bytes sent in {1} seconds.\n",
numberOfLoops * dataToSend.Length,
bufferedTime.ToString("F1"));
FlushAsync() 异步清除此流的所有缓冲区并导致所有缓冲数据都写入基础设备中
public System.Threading.Tasks.Task FlushAsync ();
返回