You cannot convert binary data directly to ASCII these days, ASCII can only represent character codes between 0 and 127. A common workaround is to use Convert.ToBase64String to convert binary data into a Base64 encoding string that only uses ASCII characters...
You can write strings to binary and read binary to string as follows:
// ASCII Content string ContentOfTheFile = "This is a sample text prepared for ysrini!"; long MoreContent = 5000;
// We write the binary file using (FileStream TargetFile = new FileStream("C:\\Test.bin", FileMode.Create, FileAccess.Write)) {
BinaryWriter MyWriter = new BinaryWriter(TargetFile); MyWriter.Write(ContentOfTheFile); // as string MyWriter.Write(MoreContent); // as binary
}
// Read the binary into a string using (FileStream ReadFile = new FileStream("C:\\Test.bin", FileMode.Open, FileAccess.Read)) { BinaryReader MyReader = new BinaryReader(ReadFile); string ReadContent = MyReader.ReadString(); long ReadCharContent = MyReader.ReadInt64();
Debug.WriteLine("Your string content: " + ReadContent + " and number " + ReadCharContent.ToString());
Convert Binary file to Ascii and vice versa
MShetty
dariodario
Hi,
You can write strings to binary and read binary to string as follows:
// ASCII Content
string ContentOfTheFile = "This is a sample text prepared for ysrini!";
long MoreContent = 5000;
// We write the binary file
using (FileStream TargetFile = new FileStream("C:\\Test.bin", FileMode.Create, FileAccess.Write))
{
BinaryWriter MyWriter = new BinaryWriter(TargetFile);
MyWriter.Write(ContentOfTheFile); // as string
MyWriter.Write(MoreContent); // as binary
}
// Read the binary into a string
using (FileStream ReadFile = new FileStream("C:\\Test.bin", FileMode.Open, FileAccess.Read))
{
BinaryReader MyReader = new BinaryReader(ReadFile);
string ReadContent = MyReader.ReadString();
long ReadCharContent = MyReader.ReadInt64();
Debug.WriteLine("Your string content: " + ReadContent + " and number " + ReadCharContent.ToString());
}
Hope this helps
Cheers