代码改变世界

StreamWriter vs BinaryWriter

2011-09-06 07:53  symphony2010  阅读(232)  评论(0编辑  收藏  举报

再用BinaryWriter写到一个txt文件里发现,里面的格式没有正常显示(显示为 带黑色矩形):

a

然后就反汇编了这两个类(reflactor):

BinaryWriter

public virtual void Write(string value)
{
    int num1 = 0;
    char* chrPointer = null;
    if (value == null)
    {
        throw new ArgumentNullException("value");
    }
    int byteCount = this._encoding.GetByteCount(value);
    this.Write7BitEncodedInt(byteCount);
    if (this._largeByteBuffer == 0)
    {
        this._largeByteBuffer = new byte[256];
        this._maxChars = 256 / this._encoding.GetMaxByteCount(1);
    }
    if (byteCount <= 256)
    {
        this._encoding.GetBytes(value, 0, value.Length, this._largeByteBuffer, 0);
        this.OutStream.Write(this._largeByteBuffer, 0, byteCount);
        return;
    }
    int num2 = 0;
    for (int i = value.Length; i > 0; i = i - num1)
    {
        num1 = (i > this._maxChars ? this._maxChars : i);
        fixed (string str = value)
        {
            if (byte[] numArray = this._largeByteBuffer || (int)numArray.Length == 0)
            {
                fixed (byte* numPointer = (byte*)((UIntPtr)0))
                {
                }
            }
            numPointer = numArray[0];
            int bytes = this._encoder.GetBytes(chrPointer + num2, num1, (IntPtr)numPointer, 256, num1 == i);
            fixed (numPointer = (byte*)((UIntPtr)0))
            {
                this.OutStream.Write(this._largeByteBuffer, 0, bytes);//在该方法下调试进入发现了InternalBlockCopy
                num2 = num2 + num1;
            }
        }
    }

}

StreamWriter

public override void Write(string value)
    {
      if (value != null)
      {
        int length = value.Length;
        int sourceIndex = 0;
        while (length > 0)
        {
          if (this.charPos == this.charLen)
          {
            this.Flush(false, false);
          }
          int count = this.charLen - this.charPos;
          if (count > length)
          {
            count = length;
          }
          value.CopyTo(sourceIndex, this.charBuffer, this.charPos, count);
          this.charPos += count;
          sourceIndex += count;
          length -= count;
        }
        if (this.autoFlush)
        {
          this.Flush(true, false);
        }
      }
    }

InternalBlockCopy(array, offset, this._buffer, this._writePos, byteCount);

wstrcpy(chRef2 + destinationIndex, chRef + sourceIndex, count);

最后发现这两个类的差别就是以上两个方法的差别。