-3

I want to read any file as binary 0 and 1 (txt,exe,png,whatever) then i want to do something to this 0 and 1 ones am done i want to recreate that file , if for example that file was .png then i want the new image to be working . with note that i know that changing the 0 and 1 may damage the file but i do know what am doing to this 0 and 1

i can read the file as 0 and 1 with the following code and write it to txt file but what i want is to recreate the original file after editing the 0 and 1 and that file should work

string inputFilename = @"/xx/xxx/xxx/xxx/folder/original.jpg"; string outputFilename = @"/xx/xxx/xxx/xxx/folder/New.txt";

    byte[] fileBytes = File.ReadAllBytes(inputFilename);
    StringBuilder sb = new StringBuilder();

    foreach (byte b in fileBytes)
    {
        sb.Append(Convert.ToString(b, 2).PadLeft(8, '0'));
    }

    File.WriteAllText(outputFilename, sb.ToString());

i expect to read anyfile as binary , do something to 0 and 1 , recreate the file again

  • Not exactly clear where you are stuck... or even why you picking text route... Maybe https://stackoverflow.com/questions/3230830/bit-manipulation-in-c-sharp-using-a-mask can help you with clarifying what you don't understand? – Alexei Levenkov May 21 '19 at 00:12
  • I don't understand how can you create original file after modifying its contents. – Chetan May 21 '19 at 00:15
  • hmm , lets say i will not change anything in the file , i just want to read its binary data then recreate that file , what is the code to recreate the file from binary data – Dholfaqar Mohammed Alharazi May 21 '19 at 00:23
  • @AlexeiLevenkov , the link you provide is nothing related to my question . Where am stuck at , is recreating the file from binary data 0 and 1 – Dholfaqar Mohammed Alharazi May 21 '19 at 00:25
  • 2
    You read all *bytes*, convert it to a string, then write out 1's and 0's *as a text string*. Everything you do with the string handling is incorrect in modifying a binary file. This is some very basic stuff... – Ron Beyer May 21 '19 at 00:53
  • 1
    As @RonBeyer said whatever you are doing makes not sense... I gave you link that is a sensible way of playing with bits assuming changing bits in a binary file is what you are after - sorry for complete misunderstanding of your question... But here is duplicate you are looking for https://stackoverflow.com/questions/3436398/convert-a-binary-string-representation-to-a-byte-array (if that is not enough try https://www.bing.com/search?q=c%23+convert+binary+to+bytes) – Alexei Levenkov May 21 '19 at 01:35

1 Answers1

1
var byteData = File.ReadAllBytes(inputFileName);
var bitData = new BitArray(byteData);

for(var i = 0; i < bitData.Length; i++)
{
    // do something to bitData[i] as bool values(true as 1 and false as 0);
}

bitData.CopyTo(byteData, 0);
File.WriteAllBytes(outputFileName, byteData);
Alsein
  • 4,268
  • 1
  • 15
  • 35