Extract Text From A Binary File - C# Programming Exercise

This exercise involves creating a C# program that extracts only the alphabetic characters contained in a binary file and dumps them to a separate file. The program should read the binary file, filter characters whose ASCII code is between 32 and 127, or equal to 10 or 13 (representing new line and carriage return, respectively), and then write these extracted characters to a new file. This exercise involves handling binary files, manipulating data based on their ASCII codes, and creating output files containing only printable characters

 Category

File Management

 Exercise

Extract Text From A Binary File

 Objective

Create a program that extracts only the alphabetic characters contained in a binary file and dumps them to a separate file. The extracted characters should be those whose ASCII code is between 32 and 127, or equal to 10 or 13.

 Write Your C# Exercise

// Import the necessary namespaces for file handling and basic input/output operations
using System;  
using System.IO;  

// Declare the main Program class
class Program
{
    // Main method where the program starts
    static void Main()
    {
        // Specify the input binary file and output text file paths
        string inputFilePath = "input.bin";  // Replace with the path to your binary file
        string outputFilePath = "output.txt";  // Replace with the desired output file path

        // Try to process the binary file and extract printable characters
        try
        {
            // Open the input binary file using a BinaryReader
            using (BinaryReader reader = new BinaryReader(File.Open(inputFilePath, FileMode.Open)))
            {
                // Create a StreamWriter to write the extracted characters to the output file
                using (StreamWriter writer = new StreamWriter(outputFilePath))
                {
                    // Read the entire file byte by byte
                    while (reader.BaseStream.Position < reader.BaseStream.Length)
                    {
                        // Read the next byte from the file
                        byte b = reader.ReadByte();

                        // Check if the byte represents an ASCII character between 32 and 127, or is 10 (newline) or 13 (carriage return)
                        if ((b >= 32 && b <= 127) || b == 10 || b == 13)
                        {
                            // Write the character to the output file
                            writer.Write((char)b);
                        }
                    }
                }
            }

            // Notify the user that the extraction was successful
            Console.WriteLine($"Extracted text has been saved to '{outputFilePath}'");
        }
        catch (Exception ex)  // Catch any errors that may occur during file reading or writing
        {
            // Print the error message to the console
            Console.WriteLine($"Error processing the file: {ex.Message}");
        }
    }
}

 Share this C# exercise

 More C# Programming Exercises of File Management

Explore our set of C# programming exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.

  •  C# to Pascal converter

    This exercise involves creating a C# program that converts simple C# programs to their equivalent in the Pascal language. The program should read C# cod...

  •  Dump

    This exercise involves creating a "dump" utility: a hex viewer that displays the contents of a file, with 16 bytes per row and 24 rows per screen. The program should pause a...

  •  DBF extractor

    This exercise involves creating a program that displays the list of fields stored in a DBF file. The DBF format is used by the old dBase database manager and is still suppor...

  •  Text censorer

    This exercise involves creating a program to censor text files. The program should read a text file and output its contents to a new file, replacing certain words with "[CEN...

  •  SQL to text

    In this exercise, you need to create a C# program capable of parsing SQL INSERT commands and extracting their data into separate lines of text. The program should pro...

  •  PGM viewer

    The PGM format is one of the versions of the NetPBM image formats. Specifically, it is the variant capable of handling images in shades of gray. Its header starts with a line conta...