Programming Course in C# ¡Free!

Extract text from a binary file

 Saturday, April 06, 2013 published by Exercises C#
Proposed exercise

Create a program to extract (only) the alphabetic characters contained in a binary file, and dump them to a different file. The extracted characters must be those whose ASCII code is 32 to 127, or 10, or 13.

Output



Solution


using System;
using System.IO;

class FileBinary
{
static void Main()
{
Console.WriteLine("Enter the name: ");
string name = Console.ReadLine();

if (!File.Exists(name))
{
Console.WriteLine("Not found {0}", name);
return;
}


try
{
FileStream file = File.OpenRead(name);
byte[] data = new byte[file.Length];
file.Read(data, 0, (int)file.Length);
file.Close();

StreamWriter newFile = new StreamWriter(name + ".new.data");
for (int i = 0; i < data.Length; i++)
{
if ((Convert.ToInt32(data[i]) >= 32) &&
(Convert.ToInt32(data[i]) <= 127) ||
(Convert.ToInt32(data[i]) == 10) ||
(Convert.ToInt32(data[i]) == 13))
{
newFile.Write(Convert.ToChar(data[i]));
}
}

newFile.Close();
}
catch (Exception)
{
Console.WriteLine("Error");
}
}
}