为什么的BinaryWriter prePEND胡言乱语到流的开始?你如何避免呢? [英] Why does BinaryWriter prepend gibberish to the start of a stream? How do you avoid it?

查看:271
本文介绍了为什么的BinaryWriter prePEND胡言乱语到流的开始?你如何避免呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我调试与写作部分的目的是文件的一些问题,我已经得到了下来,只是打开文件,并在其写入TEST的基本情况。我被像这样:

 静态的FileStream FS;
静态的BinaryWriter瓦;
FS =新的FileStream(文件名,FileMode.Create);
W =新的BinaryWriter(FS);

w.Write(测试);

w.Close();
fs.Close();
 

不幸的是,这结束了prepending一个框,该文件的前面,它看起来像这样:

测试,与前面一个有趣的盒子。这是为什么,我怎么能避免呢?

编辑:这似乎没有在这里显示框,但它看起来像乱码的UNI code字

解决方案

他们没有字节顺序标记,但一个长度 - preFIX,根据的 MSDN

 公共虚拟无效写入(字符串值);
 

  

写入pfixed字符串到长度 - $ P $   [中]流

和你需要的长度 - preFIX如果你想读的字符串,从该点回来。请参阅<一href="http://msdn.microsoft.com/en-us/library/system.io.binaryreader.readstring.aspx"><$c$c>BinaryReader.ReadString().

其他

因为它似乎你真正想要一个文件头检查

  1. 这是个问题吗?你读的长度 - preFIX回来,为的文件类型,检查它的工作原理确定

  2. 您可以将字符串转换为一个byte []数组,可能使用Encoding.ASCII。但母鸡,你必须要么使用一个固定的(隐含的)长度或... preFIX它自己。看完字节[]可以再次将其转换为字符串。

  3. 如果你有大量的文字来写你甚至可以附加的TextWriter以相同的流。但要小心,作家要关闭其流。我不会劝告这个情况的,但它是很好的了解。这里也你必须标记一个点,其他的读者可以接管(固定头工程确定)。

I'm debugging some issues with writing pieces of an object to a file and I've gotten down to the base case of just opening the file and writing "TEST" in it. I'm doing this by something like:

static FileStream fs;
static BinaryWriter w;
fs = new FileStream(filename, FileMode.Create);
w = new BinaryWriter(fs);

w.Write("test");

w.Close();
fs.Close();

Unfortunately, this ends up prepending a box to the front of the file and it looks like so:

TEST, with a fun box on the front. Why is this, and how can I avoid it?

Edit: It does not seem to be displaying the box here, but it's the unicode character that looks like gibberish.

解决方案

They are not byte-order marks but a length-prefix, according to MSDN:

public virtual void Write(string value);

Writes a length-prefixed string to [the] stream

And you will need that length-prefix if you ever want to read the string back from that point. See BinaryReader.ReadString().

Additional

Since it seems you actually want a File-Header checker

  1. Is it a problem? You read the length-prefix back so as a type-check on the File it works OK

  2. You can convert the string to a byte[] array, probably using Encoding.ASCII. But hen you have to either use a fixed (implied) length or... prefix it yourself. After reading the byte[] you can convert it to a string again.

  3. If you had a lot of text to write you could even attach a TextWriter to the same stream. But be careful, the Writers want to close their streams. I wouldn't advice this in general, but it is good to know. Here too you will have to mark a Point where the other reader can take over (fixed header works OK).

这篇关于为什么的BinaryWriter prePEND胡言乱语到流的开始?你如何避免呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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