using System; using System.IO; class Program { static void Main(string[] args) { string text = "Hello world!"; byte[] byteArray; using (MemoryStream stream = new MemoryStream()) { StreamWriter writer = new StreamWriter(stream); writer.Write(text); writer.Flush(); byteArray = stream.ToArray(); } Console.WriteLine(BitConverter.ToString(byteArray)); } }
using System; using System.IO; class Program { static void Main(string[] args) { byte[] byteArray; string filePath = @"C:\test.txt"; using (FileStream fileStream = new FileStream(filePath, FileMode.Open)) { MemoryStream memoryStream = new MemoryStream(); fileStream.CopyTo(memoryStream); byteArray = memoryStream.ToArray(); } Console.WriteLine(BitConverter.ToString(byteArray)); } }These examples use the System.IO namespace, which is included in the .NET framework's base class library.