Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Byte[] Array be written to a file in C#?

Tags:

c#

.net

I'm trying to write out a Byte[] array representing a complete file to a file.

The original file from the client is sent via TCP and then received by a server. The received stream is read to a byte array and then sent to be processed by this class.

This is mainly to ensure that the receiving TCPClient is ready for the next stream and separate the receiving end from the processing end.

The FileStream class does not take a byte array as an argument or another Stream object ( which does allow you to write bytes to it).

I'm aiming to get the processing done by a different thread from the original ( the one with the TCPClient).

I don't know how to implement this, what should I try?

like image 281
Roberto Bonini Avatar asked Dec 19 '08 16:12

Roberto Bonini


People also ask

How do I write a byte array to a file?

In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it in a file.

Can you print [] byte?

You can simply iterate the byte array and print the byte using System. out. println() method.

What is a byte [] in C#?

In C#, byte is the data type for 8-bit unsigned integers, so a byte[] should be an array of integers who are between 0 and 255, just like an char[] is an array of characters.

How do you assign a byte array?

Arrays. fill(). This method assigns the required byte value to the byte array in Java. The two parameters required for java.


2 Answers

Based on the first sentence of the question: "I'm trying to write out a Byte[] array representing a complete file to a file."

The path of least resistance would be:

File.WriteAllBytes(string path, byte[] bytes) 

Documented here:

System.IO.File.WriteAllBytes - MSDN

like image 149
Kev Avatar answered Sep 21 '22 16:09

Kev


You can use a BinaryWriter object.

protected bool SaveData(string FileName, byte[] Data) {     BinaryWriter Writer = null;     string Name = @"C:\temp\yourfile.name";      try     {         // Create a new stream to write to the file         Writer = new BinaryWriter(File.OpenWrite(Name));          // Writer raw data                         Writer.Write(Data);         Writer.Flush();         Writer.Close();     }     catch      {         //...         return false;     }      return true; } 

Edit: Oops, forgot the finally part... lets say it is left as an exercise for the reader ;-)

like image 22
Treb Avatar answered Sep 20 '22 16:09

Treb