articles » archived » asp-net » convert-byte-array-to-string

ASP.NET: Convert Byte Array to String

Convert a byte array to a string and a string to a byte array (.NET Framework).

When working with files that contain both binary and text, it may be useful to convert a byte array into a unicode string.

using (System.IO.FileStream fs = new System.IO.FileStream("C:\\Windows\\Temp\\tempfile.tmp", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read))
	byte[] bytes = new byte[fs.Length];
	fs.Read(bytes, (int)0, (int)fs.Length);
	string data = System.Text.Encoding.ASCII.GetString(bytes); // convert the byte array to a string
	// do something here
	bytes = System.Text.Encoding.ASCII.GetBytes(data); // convert the string back into a byte array
	using (System.IO.FileStream fs2 = new System.IO.FileStream("C:\\Images\\file.jpg", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, System.IO.FileShare.Read))
		fs2.Write(bytes, 0, bytes.Length);

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.