简体   繁体   中英

C# equivalent to VB6's 'Open' & 'Put' Functions

I will try to make this as straight forward as possible. This question does not simply involve reading and writing bytes. I am looking for an exact translation between this VB6 code and C# code. I know this is not always a posibility but I'm sure someone out there has some ideas!

VB6 Code & explanation:

The below code writes data into a specific part of the file.

[ Put [#]filenumber, [byte position], varname ].

It is the *byte position * that I am having trouble figuring out - and help with this would be very much appreciated!

Dim file, stringA as string

Open file for Binary As #1
    lPos = 10,000
    stringA = "ThisIsMyData"
Put #1, lPos, stringA

Close #1

So, I am looking for some help with the byte position, once again. In this example the byte position was represented by lPos.

EDIT FOR HENK -

I will be reading binary data. There are some characters in this binary data that I will need to replace . For this reason, I will be using VB6's instr function to get the poisition of this data (there lengths are previously known). I will then use Vb6's Put function to write this data at the newfound position. This will overwrite the old data with the new data. I hope this helped!

If it helps anyone, here is some further information regarding the Put function.

Thanks so much, Evan

Can you not use a BinaryWriter ?

For example:

FileStream fs = new FileStream(file, FileMode.Open);
BinaryWriter w = new BinaryWriter(fs);

w.Seek(10000, SeekOrigin.Origin);
w.Write(encoding.GetBytes("ThisIsMyData"));

w.Flush();
w.Close();
fs.Close();

You can do this using StreamReader and StreamWriter.

I would try something like this:

  • Read the first n bits and write them into a new stream using StreamWriter.
  • Using the same StreamWriter, write the new bits that you want to insert.
  • Finally, write the rest of the bits from your StreamReader.

This question is not a perfect fit, however it shows a similiar technique using text (not binary data): Insert data into text file

看看在StreamWriter类专门在这个过载的Write方法 ,它允许你开始写作到流中的特定位置。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM