Search code examples
c#textstreambyte

using Stream writer to Write a specific bytes to textfile


Well I'm trying to write some values and strings to a text file.
but this text file must contain 2 bytes

These are the 2 bytes I want to insert to my text file after finishing writing the other values to it:

hex

I tried this method but I have no idea how to write bytes through it

using (StreamWriter sw = new StreamWriter(outputFilePath, false, Encoding.UTF8))

I have no idea about how to write them to the text file after putting the strings I want on it.


Solution

  • If I recall correctly from your question. You want to write strings to a file and then write bytes to it?

    This example will do that for you:

    using (FileStream fsStream = new FileStream("Bytes.data", FileMode.Create))
    using (BinaryWriter writer = new BinaryWriter(fsStream, Encoding.UTF8))
    {
        // Writing the strings.
        writer.Write("The");
        writer.Write(" strings");
        writer.Write(" I");
        writer.Write(" want");
        writer.Write(".");
    
        // Writing your bytes afterwards.
        writer.Write(new byte[]
                     {
                         0xff,
                         0xfe
                     });
    }
    

    When opening the "Bytes.data" file with a hex editor you should see these bytes: enter image description here