开发者

Using File class to write binary files in VB .NET

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 method开发者_如何学编程s 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.)


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()


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜