System.IO.BinaryWriter.Write 方法 (String)
方法描述
将有长度前缀的字符串按 BinaryWriter 的当前编码写入此流,并根据所使用的编码和写入流的特定字符,提升流的当前位置。
语法定义(C# System.IO.BinaryWriter.Write 方法 (String) 的用法)
public virtual void Write( string value )
参数/返回值
参数值/返回值 | 参数类型/返回类型 | 参数描述/返回描述 |
---|---|---|
value | System-String | 要写入的值。 |
返回值 | void |
提示和注释
带长度前缀的字符串通过在字符串前面放置一个包含该字符串长度的字节或单词,来表示该字符串的长度。 此方法首先将字符串的长度作为 UTF-7 编码的无符号整数写入,然后再将这些字符通过使用 BinaryWriter 实例的当前编码写入流中。
有关通用 I/O 任务的列表,请参见通用 I/O 任务。
System.IO.BinaryWriter.Write 方法 (String)例子
将显示这两个字符串检索的输出。
using System; using System.IO; using System.Text; public class BinReadWrite { public static void Main() { string testfile = @"C:\testfile.bin"; // create a test file using BinaryWriter FileStream fs = File.Create(testfile); UTF8Encoding utf8 = new UTF8Encoding(); BinaryWriter bw = new BinaryWriter(fs, utf8); string bstring; bstring = "This is line #1 of text written as a binary stream.\r\n"; bstring += "This is line #2 of text written as a binary stream.\r\n"; bstring += "This is line #3 of text written as a binary stream."; bw.Write(bstring); // reset the stream position for reading fs.Seek(0, SeekOrigin.Begin); // Read the string as raw bytes using FileStream... // The first series of bytes is the UTF7 encoded length of the // string. In this case, however, it is just the first two bytes. int len = fs.ReadByte() & 0x7f; len += fs.ReadByte() * 0x80; // read the string as bytes of length = len byte[] rawbytes = new byte[len]; fs.Read(rawbytes, 0, len); // display the string Console.WriteLine("Read from FileStream: \n" + utf8.GetString(rawbytes)); Console.WriteLine(); // Now, read the string using BinaryReader // reset the stream position for reading again fs.Seek(0, SeekOrigin.Begin); BinaryReader br = new BinaryReader(fs, utf8); // ReadString will read the length prefix and return the string. bstring = br.ReadString(); Console.WriteLine("Read from BinaryReader: \n" + bstring); fs.Close(); } } //The output from the program is this: // // Read from FileStream: // This is line #1 of text written as a binary stream. // This is line #2 of text written as a binary stream. // This is line #3 of text written as a binary stream. // // Read from BinaryReader: // This is line #1 of text written as a binary stream. // This is line #2 of text written as a binary stream. // This is line #3 of text written as a binary stream.
异常
异常 | 异常描述 |
---|---|
IOException | 发生 I/O 错误。 |
ArgumentNullException | value 为 null。 |
ObjectDisposedException | 流已关闭。 |
版本信息
.NET Framework 受以下版本支持:4、3.5、3.0、2.0、1.1、1.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 系统要求。