为什么TFileStream的WriteBuffer方法要写定长的Byte数组数据才正确?
代码如下:
procedure TForm1.Button1Click(Sender: TObject);
var
  fs: TFileStream;
  bf: array of byte;
begin
  SetLength(b,10);
  bf[0] := $FF;
  bf[1] := $FF;
  Bf[2] := $FF;  fs := TFileStream.Create('C:\aaa.data',fmCreate);
  fs.WriteBuffer(b,10);
  fs.Free;
  fs := Nil;
end;写出的文件内容不正确.而将bf: array of byte动态数组改成静态的bf: array[0..9] of byte就正常.若一定要写动态的应该如何处理?

解决方案 »

  1.   

    procedure TForm1.Button1Click(Sender: TObject);
    var
      fs: TFileStream;
      bf: array of byte;
    begin
      SetLength(bf,3);
      bf[0] := $FF;
      bf[1] := $FF;
      Bf[2] := $FF;  fs := TFileStream.Create('C:\aaa.data',fmCreate);
      fs.WriteBuffer(bf[0],3);
      FreeAndNil(fs);
    end;
      

  2.   

    真是个闹心的问题,好象liangqingzhi(老之)的也不行啊。我变通了一下,问题是解决了,但有点不是很符合逻辑,贴出来,大家讨论讨论。function BytesToString(Bytes:Array of Byte):String;
    var
      Idx: integer;
      StrTmp: string;
      Count: word;
    begin
      StrTmp := '';
      Count := Length(Bytes);
      for Idx := 0 to Pred(Count) do
        StrTmp := StrTmp + IntToHex(Bytes[Idx],2) + ' ';
      Result := StrTmp;
    end;procedure TForm1.Button1Click(Sender: TObject);
    var
      Buffer: array of byte;
      Stream: TFileStream;
      StrBuf: string;
    begin
      SetLength(Buffer, 10);
      Buffer[0] := $FF;
      Buffer[1] := $FF;
      Buffer[2] := $FF;
      Stream := TFileStream.Create('C:\WHAT.TXT', fmCreate);
      StrBuf := BytesToString(Buffer);
      Stream.WriteBuffer(Pointer(StrBuf)^, Length(StrBuf));
      FreeAndNil(Stream);
    end;结果 = FF FF FF 00 00 00 00 00 00 00
      

  3.   

    我的代码应该没问题的,用UltraEdit打开文件,选十六进制编辑就可以看到内容了。