tags:

views:

2011

answers:

7

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?

A: 

Yep, why not?

fs.Write(myByteArray, 0, myByteArray.Length);
Mehrdad Afshari
+13  A: 

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:

http://msdn.microsoft.com/en-us/library/system.io.file.writeallbytes.aspx

Kev
Thanks. Should have seen this myself earlier.
Roberto Bonini
Done it myself, sometimes can't see the wood for the trees :)
Kev
+5  A: 

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

Treb
+1  A: 

You can do this using System.IO.BinaryWriter which takes a Stream so:

var bw = new BinaryWriter(File.Open("path",FileMode.OpenOrCreate);
bw.Write(byteArray);
JoshBerke
+2  A: 

There is a static method System.IO.File.WriteAllBytes

Andrew Rollings
A: 

Doesn't the FileStream have a write method that accepts a byte[] array? Not sure if I fully get your question...

BFree
A: 

You can use the FileStream.Write(byte[] array, int offset, int count) method to write it out.

If your array name is "myArray" the code would be.

myStream.Write(myArray, 0, myArray.count);
Mitchel Sellers