Are the binary reader and writer open at the same time?

I am writing code that processes a file that uses hashes. I need to read a piece, then hash it, then write it, then read another piece, etc.

In other words, I need to read and write a lot. I'm sure it is really simple, but I just wanted to run it by professionals ...

Is it possible and permissible to do something like:

BinaryReader br = new BinaryReader (File.OpenRead(path)); BinaryWriter bw = new BinaryWriter (File.OpenWrite(path)); br.dostuff(); bw.dostuff(); 

I remember how I came across some kind of conflicting file stream problem when experimenting with opening and writing files, and I'm not sure what I did to get it. Is this a problem with two file streams? Can I use one stream for reading and writing?

+4
source share
1 answer

This is ideal and desirable, technical, if your writing method does not change the file length and always stands behind the reader, this should not create any problems. In fact, from an API point of view, this is desirable as it allows the user to control where to read and where to write. (This is the recommended specification for writing to another file, in case of any bad events during the encryption process, your input file will not be corrupted).

Sort of:

 protected void Encrypt(Stream input, Stream output) { byte[] buffer = new byte[2048]; while (true) { // read int current = input.Read(buffer, 0, buffer.Length); if (current == 0) break; // encrypt PerformActualEncryption(buffer, 0, current); // write output.Write(buffer, 0, current); } } public void Main() { using (Stream inputStream = File.Open("file.dat", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (Stream outputStream = File.Open("file.dat", FileMode.Open, FileAccess.Write, FileShare.ReadWrite)) { Encrypt(inputStream, outputStream); } } 

Now that you are using encryption, I would even recommend doing the actual encryption in another specialized thread. This clears the code well.

 class MySpecialHashingStream : Stream { ... } protected void Encrypt(Stream input, Stream output) { Stream encryptedOutput = new MySpecialHashingStream(output); input.CopyTo(encryptedOutput); } 
+2
source

Source: https://habr.com/ru/post/1388239/


All Articles