Byte Array to a text file

C# is renowned for being a strongly typed language, which implies that every object utilized or created within a C# program must possess a specific type. In this context, "byte" serves as an example of an immutable value type, adept at representing unsigned integers within a range spanning from 0 to 255.

FileStream class

Let's now examine a practical scenario where we utilize an instance of the FileStream class. This class allows us to interact with files in a stream-oriented manner. In this particular case, we utilize the Write() method, which enables us to write a block of bytes to the current stream. The Write() method accomplishes this task by utilizing data retrieved from a buffer.

oFileStream.Write(byteData, 0, byteData.Length);

The following C# program shows how to write the content of a Byte Array into a Text file.

using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string str = "https://net-informations.com/csharp/default.htm"; System.Text.UTF8Encoding encod = new System.Text.UTF8Encoding(); byte[] byteData = encod.GetBytes(str); System.IO.FileStream oFileStream = null; oFileStream = new System.IO.FileStream("c:\\bytes.txt", System.IO.FileMode.Create); oFileStream.Write(byteData, 0, byteData.Length); oFileStream.Close(); } } }

Conclusion

Using this approach, we can efficiently transfer data from the buffer to the stream, facilitating various file-related operations in a seamless and efficient manner. The Write() method serves as a fundamental tool within the C# ecosystem, enabling developers to perform crucial operations such as saving data or transmitting it to external devices.