日期:2014-05-16  浏览次数:20993 次

为什么BinaryWriter也能以文本方式写入? 但是写入的有乱码
通常,我们要对文件写入文本信息,都是用StreamWriter来包装一个FileStream。但是我发现BinaryWriter.Write也可以是用string类型作为输入参数,像下面这样:

            FileStream f = null;
            StreamWriter sw = null;
            try
            {
                f = File.Open(@"d:\my.txt", FileMode.OpenOrCreate, FileAccess.Write);
                sw = new StreamWriter(f);
                sw.Write("haha");

                bw = new BinaryWriter(f);
                bw.Write("haha");既然是BinaryStream,为什么仍然可以写入一个Ansi字符串? 
            }

我查看D:\下面的my.txt文件,发现一共写了5个字节,第一个字节是乱码。剩下4个字节才是"haha"。这到底是怎么回事呢? 
另外,用Write函数来写字符串的话,默认encoding是Ansi还是根据当前操作系统的语言来设定?

还请高手答疑!
------解决方案--------------------
bw = new BinaryWriter(f);
 bw.Write("haha");
这个与StreamWriter 的Write是不一样的

StreamWriter 他是直接写字符串到文本不加工的

BinaryWriter 他是写字节流 有做了加工内部会写两次
 他是先把字符串转成byte[]  xxx
再把 int iLen=xxx.Length
再把int转成4个字节的byte[] buffLen=iLen;
Write(buffLen); <--你看到的乱码就是这个buffLen的字节流
Write(xxx);
还有BinaryWriter 多数用于网络的Socket传输 
当然写文件也可以,其内容不是文本,应是字节流。像我们打开的视频,图片文件 这类的,都是字节流,他们格式有规定的。
像头X个字节是为文件头第X-1到X+8个字节为文件的内容大小

------解决方案--------------------
        //
        // Summary:
        //     Initializes a new instance of the System.IO.BinaryWriter class based on the
        //     supplied stream and using UTF-8 as the encoding for strings.
        //
        // Parameters:
        //   output:
        //     The output stream.
        //
        // Exceptions:
        //   System.ArgumentException:
        //     The stream does not support writing, or the stream is already closed.
        //
        //   System.ArgumentNullException:
        //     output is null.