410

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?

George Stocker
  • 57,289
  • 29
  • 176
  • 237
Roberto Bonini
  • 7,164
  • 6
  • 39
  • 47

9 Answers9

831

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

Kev
  • 118,037
  • 53
  • 300
  • 385
45

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

Odys
  • 8,951
  • 10
  • 69
  • 111
Treb
  • 19,903
  • 7
  • 54
  • 87
  • Lets say, I have received compressed data, and I have decompressed it to Byte[]. Is it possible to create the file back using above function ? Any tutorial or demo online ? – Cannon Jun 15 '11 at 03:52
  • @buffer_overflow: You would need to compress it first if you want to get the original file back. Have a look at the Decorator Pattern for a possible implementation: http://en.wikipedia.org/wiki/Decorator_pattern – Treb Jun 15 '11 at 10:52
  • 3
    `BinaryWriter` is disposable so should probably be used within an `using` block. That'd also mean you could probably leave off some of the extra calls since the [source code](https://referencesource.microsoft.com/#mscorlib/system/io/binarywriter.cs,51545ac4b683f454) shows that it does some cleanup while disposing. – Jeff B Mar 31 '17 at 13:39
  • 1
    Why swallow the exception and return true/false? Daft. – bytedev Oct 15 '21 at 08:18
24

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

Andrew Rollings
  • 14,340
  • 7
  • 51
  • 50
12

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);
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
JoshBerke
  • 66,142
  • 25
  • 126
  • 164
9

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
  • 62,228
  • 14
  • 110
  • 173
7

Yep, why not?

fs.Write(myByteArray, 0, myByteArray.Length);
Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
2

Try BinaryReader:

/// <summary>
/// Convert the Binary AnyFile to Byte[] format
/// </summary>
/// <param name="image"></param>
/// <returns></returns>
public static byte[] ConvertANYFileToBytes(HttpPostedFileBase image)
{
    byte[] imageBytes = null;
    BinaryReader reader = new BinaryReader(image.InputStream);
    imageBytes = reader.ReadBytes((int)image.ContentLength);
    return imageBytes;
}
Graham
  • 7,431
  • 18
  • 59
  • 84
PatsonLeaner
  • 1,230
  • 15
  • 26
1

Asp.net (c#)

// This is server path, where application is hosted.

var path = @"C:\Websites\mywebsite\profiles\";

//file in bytes array

var imageBytes = client.DownloadData(imagePath);

//file extension

var fileExtension = System.IO.Path.GetExtension(imagePath);

//writing(saving) the files on given path. Appending employee id as file name and file extension.

File.WriteAllBytes(path + dataTable.Rows[0]["empid"].ToString() + fileExtension, imageBytes);

Next Step:

You may need to Provide access to profile folder for iis user.

  1. right click on profile folder
  2. go to security tab
  3. click "Edit",
  4. give full control to "IIS_IUSRS" (IF THIS USER NOT EXISTS THEN CLICK ON ADD AND TYPE "IIS_IUSRS" AND CLICK ON "Check Names".
0

For completeness, there is also an async version of the System.IO.File.WriteAllBytes() method:

Task WriteAllBytesAsync (string path, byte[] bytes, CancellationToken cancellationToken = default);

Example usage (in an async method):

await File.WriteAllBytesAsync("C:\\Test.png", bytes);

Note that since writing to a file is an IO operation, as a general rule it must be performed asynchronously not to block the UI.

Mustafa Özçetin
  • 1,893
  • 1
  • 14
  • 16