Streams in .NET
Streams in .NET
.NET中Stream的继承图
I/O的同步异步操作
.NET中对于I/O的操作有同步和异步之分。
在进行同步I/O操作时,当前进程会被阻塞直到I/O操作完毕。当我们程序读取或写入的内容比较少的时候可以使用这样的同步方法,但是当我们进行大块数据的操作时,这样的同步方法显然是不适合的。尤其对于网络流,I/O操作受到网速等诸多因素的影响,同步难以使用。
对于异步I/O操作,程序进行流处理时会独立创建一个I/O操作的线程,在操作完成之前我们任然可以做其它的工作,当I/O处理完毕后操作系统会通知调用者。
各种Stream用途
同步读写方法
异步读写方法
FileStream类
FileStream out =
new FileStream("D:\\MyStream.txt",
FileMode.Open, FileAccess.Write,
FileShare.Read, 1000, true);
参数1:打开的文件路径
参数2:打开模式
参数3:访问模式
参数4:共享权限
参数5:缓冲区大小
参数6:同步或异步状态(true表示异步)
BufferedStream类
BufferedStream类主要用来提高不同传送速度设备之间的传输效率,默认缓冲区大小为4KB。通常与NetWordStream协同使用在内存中存储数据。
//
Reading BufferedStream
public static void readBufStream(Stream st)
{
// Compose
BufferedStream
BufferedStream bf = new
BufferedStream(st);
byte[]
inData = new Byte[st.Length];
// Read and
display buffered data
bf.Read(inData, 0, Convert.ToInt32(st.Length));
Console.WriteLine(Encoding.ASCII.GetString(inData));
}
MemoryStream类
当一个应用程序需要经常读取一些数据时,我们将这些数据存入MemoryStream中可以提高应用程序的效率。尤其对于对象的序列化存储,以MemoryStream存储比BufferedStream和FileStream的效率要高。
namespace Hello
{
//
class Program
{
static void Main(string[]
args)
{
// Create
empty Memory stream
MemoryStream
mS = new MemoryStream();
byte[]
memData = Encoding.ASCII.GetBytes("This will go in Memory!!");
// Write data
mS.Write(memData, 0, memData.Length);
// Set pointer
at origin
mS.Position = 0;
byte[]
inData = new byte[100];
// Read memory
mS.Read(inData, 0, 100);
Console.WriteLine(Encoding.ASCII.GetString(inData));
Stream
strm = new FileStream("C:\\MemOutput.txt",
FileMode.OpenOrCreate,
FileAccess.Write);
mS.WriteTo(strm);
}
}
}
NetworkStream类
NetworkStream没有缓冲区,不支持内容的随机访问,通常使用BufferedStream作为存储的中间介质。
TCP服务端代码示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net.Sockets;
namespace Hello
{
//
class Program
{
static void Main(string[]
args)
{
try
{
// Create
TCP listener
TcpListener
listener = new TcpListener(5001);
listener.Start();
TcpClient
tc = listener.AcceptTcpClient();
NetworkStream
stm = tc.GetStream();
byte[]
readBuf = new byte[100];
stm.Read(readBuf, 0, 100);
//Display
Data
Console.WriteLine(Encoding.ASCII.GetString(readBuf));
stm.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
TCP客户端代码示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net.Sockets;
namespace Hello
{
//
class Program
{
static void Main(string[]
args)
{
try
{
// Create
TCP Client
TcpClient
client = new TcpClient();
//Connect
using hostname and port
client.Connect("localhost", 5001);
//Get
NetworkStream instance for sending data
NetworkStream
stm = client.GetStream();
byte[]
sendBytes = Encoding.ASCII.GetBytes("This data has come from another place!!!");
stm.Write(sendBytes, 0,
sendBytes.Length);
client.Close();
}
catch (Exception
e)
{
Console.WriteLine(e.ToString());
Console.WriteLine("The listener has probably not started");
}
}
}
}
CryptoStream类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;
namespace Hello
{
//
class Program
{
static void Main(string[]
args)
{
Console.WriteLine("Select Service Provider for CryptoStream");
Console.WriteLine("1 = DESCryptoServiceProvider");
Console.WriteLine("2 = RC2CryptoServiceProvider");
Console.WriteLine("3 = RijndaelManaged");
Console.WriteLine("4 = TripleBESCryptoServiceProvider");
Console.WriteLine("5 = SymmetricAlgorithm");
// Create des
object
SymmetricAlgorithm
des = null;
switch (Console.ReadLine())
{
case "1":
des = new
DESCryptoServiceProvider();
break;
case "2":
des = new
RC2CryptoServiceProvider();
break;
case "3":
des = new
RijndaelManaged();
break;
case "4":
des
= new TripleDESCryptoServiceProvider();
break;
case "5":
des = SymmetricAlgorithm.Create();
//uses default algorithm
break;
default:
Console.WriteLine("Wrong selection");
return;
}
FileStream
fs = new FileStream("SecretFile.dat", FileMode.Create,
FileAccess.Write);
ICryptoTransform
desencrypt = des.CreateEncryptor();
CryptoStream
cryptostream = new CryptoStream(fs,
desencrypt,
CryptoStreamMode.Write);
string
theMessage = "A top secret message";
byte[]
bytearrayinput = Encoding.Unicode.GetBytes(theMessage);
Console.WriteLine("Original Message : {0} ", theMessage);
cryptostream.Write(bytearrayinput, 0,
bytearrayinput.Length);
cryptostream.Close();
fs.Close();
/***********Time
to Decrypt...************/
// Create file
stream to read encrypted file back
FileStream
fsread = new FileStream("SecretFile.dat", FileMode.Open,
FileAccess.ReadWrite);
byte[]
encByte = new byte[fsread.Length];
fsread.Read(encByte, 0, encByte.Length);
Console.WriteLine("Encrypted Message : " +
Encoding.ASCII.GetString(encByte));
fsread.Position = 0;
// Create DES
Decryptor from our des instance
ICryptoTransform
desdecrypt = des.CreateDecryptor();
CryptoStream
cryptostreamDecr = new CryptoStream(fsread,
desdecrypt,
CryptoStreamMode.Read);
byte[]
decrByte = new byte[fsread.Length];
cryptostreamDecr.Read(decrByte, 0, (int)fsread.Length);
string
output = Encoding.Unicode.GetString(decrByte);
Console.WriteLine("Decrypted Message : {0}", output);
cryptostreamDecr.Close();
fsread.Close();
}
}
}