0

I want to be able to read and write into a file in the same instance or through same file handle. What I mean is this. Say you open a file as follows.

BinaryReader jfile := new BinaryReader(File.OpenRead('c:\jokes.dat'));

I want to be able to also write into the file without having to close the jfile handle and then call BinaryWriter to be able to write into the file. Can you do that?

Also, once you open a file to be written, any data in the old file with a same name will be completely erased. Is that true?

I know you can do this for Win32 as Follows without having to reassign f file handle.

Assignfile(f,fname);
Reset(f,1);
BlockRead(f,jokeA,SizeOf(jokeA));

Reset(f,1);
BlockWrite(f,jokeB,SizeOf(jokeB));
CloseFile(f);
ThN
  • 3,235
  • 3
  • 57
  • 115
  • This is a duplicate of [Binary reader and writer open at same time](http://stackoverflow.com/questions/8652045/binary-reader-and-writer-open-at-same-time), except that one has a C# tag and yours has .net and delphi-prism. Perhaps it will help. – Ken White Apr 25 '12 at 17:20
  • @KenWhite Thanks I didn't see that question – ThN Apr 25 '12 at 19:10

2 Answers2

1

FWIW, I don't think you can do that with the Binary* classes. You can use the FileStream class, though. Also, FWIW, the classic Pascal/Delphi Reset(File) command actually opens a new handle - it's only the file variable (essentially the file name) that's reused.

1

you can:

using lFile := File.Open('c:\jokes.dat', FileMode.ReadWrite) do begin
  var lReader := new BinaryReader(lFile);
  // read using reader

  lFile.Position := lFile.Length;
  var lWriter := new BinaryWriter(lFile);
  lWriter.Write...

end;
Carlo Kok
  • 1,128
  • 5
  • 14