System.IO.UnmanagedMemoryStream.WriteByte 方法
方法描述
将一个字节写入文件流的当前位置。
语法定义(C# System.IO.UnmanagedMemoryStream.WriteByte 方法 的用法)
public override void WriteByte( byte value )
参数/返回值
参数值/返回值 | 参数类型/返回类型 | 参数描述/返回描述 |
---|---|---|
value | System-Byte | 写入流的字节值。 |
返回值 | void |
提示和注释
System.IO.UnmanagedMemoryStream.WriteByte 方法例子
在此示例中,UnmanagedMemoryStream 对象将被传递给一个方法,该方法在尝试将数据写入流中之前检查 CanWrite 属性。
// Note: You must compile this sample using the unsafe flag. // From the command line, type the following: csc sample.cs /unsafe using System; using System.IO; using System.Runtime.InteropServices; using System.Text; unsafe class Program { static void Main() { // Create some data to write. byte[] text = UnicodeEncoding.Unicode.GetBytes("Data to write."); // Allocate a block of unmanaged memory. IntPtr memIntPtr = Marshal.AllocHGlobal(text.Length); // Get a byte pointer from the unmanaged memory block. byte* memBytePtr = (byte*)memIntPtr.ToPointer(); UnmanagedMemoryStream writeStream = new UnmanagedMemoryStream( memBytePtr, text.Length, text.Length, FileAccess.Write); // Write the data. WriteToStream(writeStream, text); // Close the stream. writeStream.Close(); // Create another UnmanagedMemoryStream for reading. UnmanagedMemoryStream readStream = new UnmanagedMemoryStream(memBytePtr, text.Length); // Display the contents of the stream to the console. PrintStream(readStream); // Close the reading stream. readStream.Close(); // Free up the unmanaged memory. Marshal.FreeHGlobal(memIntPtr); } public static void WriteToStream(UnmanagedMemoryStream writeStream, byte[] text) { // Verify that the stream is writable: // By default, UnmanagedMemoryStream objects do not have write access, // write access must be set explicitly. if (writeStream.CanWrite) { // Write the data, byte by byte for (int i = 0; i < writeStream.Length; i++) { writeStream.WriteByte(text[i]); } } } public static void PrintStream(UnmanagedMemoryStream readStream) { byte[] text = new byte[readStream.Length]; // Verify that the stream is writable: // By default, UnmanagedMemoryStream objects do not have write access, // write access must be set explicitly. if (readStream.CanRead) { // Write the data, byte by byte for (int i = 0; i < readStream.Length; i++) { text[i] = (byte)readStream.ReadByte(); } } Console.WriteLine(UnicodeEncoding.Unicode.GetString(text)); } }
异常
异常 | 异常描述 |
---|---|
ObjectDisposedException | 流已关闭。 |
NotSupportedException |
|
IOException | 提供的 value 导致流超出它的最大容量。 |
版本信息
.NET Framework 受以下版本支持:4、3.5、3.0、2.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1
适用平台
Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。