C#Binarywriter写字符串 [英] c# binarywriter write string

查看:115
本文介绍了C#Binarywriter写字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我打算用C#中的binarywriter将char写入二进制文件:


Howdy, I intend to write char to a binary file with binarywriter in C#:


FileStream filestream = new FileStream("test.t", FileMode.Create, FileAccess.Write, FileShare.Read, 1024);
      BinaryWriter binaryWriter = new BinaryWriter(filestream);
      binaryWriter.Write("hello");
      binaryWriter.Write("AAA");
      binaryWriter.Close();
      file.Close();



但是,当我检查输出文件时,我发现每个字符串的前面都有多余的字节,因此,hello变成了六个字符: 0x05''h''''e''''l''''l ''''o''和"AAA"变成四个字符: 0x03''A''''A''''A''

有人知道为什么吗?



VS 2008
在win7和xp中进行测试.



But when I exam the output file I found there are extra bytes in the front of each string, such that the hello become six chars: 0x05 ''h''''e''''l''''l''''o'' and "AAA" become four chars: 0x03''A''''A''''A''

Anyone know why?



VS 2008
Test in win7 and xp.

推荐答案

是.

简单:前缀就是长度.如果尝试使用此处实际编写的代码(并修复编译错误-它应为"filestream.Close()"),您将发现该文件包含
Yes.

Simple: the prefix is the lengths. If you try with the code you actually wrote here, (and fix the compilation error - it should be "filestream.Close()" - you will find that the file contains
0x05  - number of characters in the string "hello"
'h'
'e'
'l'
'l'
'o'
0x03  - number of characters in the string "AAA"
'A'
'A'
'A'

您的应用程序中此版本的字符串以十个字符开头,而不是五个

The version of this in your application had a string of ten characters to start with, rather than five


字符串前面有一个长度字节,如此处 [
Strings are preceded by a length byte as described here[^]. It''s always best to read the documentation first.


如果您不需要或不需要长度字节,可以使用Char []数组而不是String调用Write.
If you don''t want or need the length byte you can call Write with a Char [] array instead of a String.


这篇关于C#Binarywriter写字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆