Create a File From Binary Data In C#

2.1k views Asked by At

I am trying to read a file in binary and create a file of the same format with that binary, this file can be in any commom format like (.docx, .txt, .jpeg, .png ) etc.

I created a text file (test.txt) that has a string This is a text string written in it.

string file = "filelocation";    //this has a file location 

byte[] data = File.ReadAllBytes(fileWithExt);     //  this gives me binary data.....

Now how do i create a file of the same extension with the binary data. ?

2

There are 2 answers

0
Dan Csharpster On BEST ANSWER

Per comment feedback, this is more about encryption than just binary file I/O.

Encryption can be done on a file after it is already saved:

https://learn.microsoft.com/en-us/dotnet/api/system.io.file.encrypt?view=net-5.0

And for basic guidance on working with encryption and files in C#, I'd suggest this Microsoft example walkthrough:

https://learn.microsoft.com/en-us/dotnet/standard/security/walkthrough-creating-a-cryptographic-application

0
Julio Cesar Araya Soto On

may be this could be helpful

// Specifing a file name 
var path = @"file.txt"; 

// Specifing a new file name 
var nPath = @"file2.txt"; 

// Calling the ReadAllBytes() function 
byte[] data = File.ReadAllBytes(path); 

// Calling the WriteAllBytes() function 
// to write the file contents with the 
// specified byte array data 
File.WriteAllBytes(nPath, data);