1

I am trying to write a simple application that monitors the COM port and writes the incoming binary data to a file. So, I gathered a File class is provided, but looking at its methods list in the Help page, I see no method for writing individual bytes (and the Write methods seem to close the file after writing).

How can I write a byte array into a file, keep it open and repeat this as necessary?

(I am using Visual Studio 2005, if it's relevant.)

3 Answers 3

2

Use a FileStream:

Dim file As FileStream = File.OpenWrite(fileName)

You use the Write method to write a byte array (or part of it) to the stream:

file.Write(buffer, 0, buffer.Length)

The Write method doesn't close the stream, you can write as many times you like.

When you have written what you want, you use the Close method to close the stream:

file.Close()
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, @Guffa, Don't I know you from somewhere? ;-) -- According to the documentation (the page I linked to in the question), the File class does not have a Write() method. So, where does this come from?
@ysap: The File class is just a static class that contains some useful static methods, but it doesn't represent an opened file. The FileStream class is what you use to handle an opened file, and it's that class that has the Write method.
I need to separate the OpenWrite operation from the Dim declaration, i.e., the file variable should be a member of the class and not a local variable. This is b/c I am opening, writing and closing in all different methods. So, I played a little with the code, but I get an error for every combination I try. Last time I programed in VB was years ago on VB6, so even I can implement this in the "old style", I am trying to make it compatible with the .NET spirit.
OK, problem solved. I defined file as FileStream without the assignment in the members area, then used file = File.OpenWrite(name,mode) in the Open method. Thanks!
2

You're looking for the BinaryWriter class, also in the System.IO namespace.

The various overloads of the Write method allow you to write values to the file, and then advance the current position in the stream by the appropriate number of bytes.

Comments

2

Use BinaryWriter.Write method:

BinaryWriter binWriter = new BinaryWriter(File.Open(@"C:\Test.txt", FileMode.Create)))

byte[] byteValue = // set the value here ..
binWriter.Write(byteValue );

Refer to:

BinaryWriter Class

2 Comments

thanks. Did you mean that the first keyword should be Dim and not BinaryWriter? Otherwise, I get an error.
Don't forget to binWriter.Close() after finishing the write.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.