SoFunction
Updated on 2025-03-07

C# Read text files in binary


using System;
using ;

public class FileApp
{
    public static void Main()
    {
// Create a file in the current directory with read and write permissions to the file
        FileStream fsMyfile = new FileStream("" , , );

// Create a data stream writer and associate it with the opened file
        StreamWriter swMyfile = new StreamWriter(fsMyfile);

// Write a file in text
        ("Hello, World");
        ("abcdefghijklmnopqrstuvwxyz");
        ("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
        ("0123456789");

// Flush data (really write the data into the file)
// Try commenting on this sentence, the program will report an error
        ();

// Read the file in text
// Create a data stream reader and associate it with the opened file
        StreamReader srMyfile= new StreamReader(fsMyfile);

// Relocate the file pointer to the beginning of the file
        (0, );

// Print prompt information
("********************* Read file in text **********************************);

// Print the file text content
        string s1;
        while((s1 = ())!=null)
        {
            (s1);
        }
        ();
// End reading the file in text


// Read files in binary
// Create a binary data stream reader and associate it with the opened file
        BinaryReader brMyfile= new BinaryReader (fsMyfile);

// Relocate the file pointer to the beginning of the file
        (0, );

// Print prompt information
("********************* Read file in binary mode****************************);

// Print the file text content
        Byte b1;
        while(()>-1)
        {
            b1=();
// 13 is "\n", indicating Enter; 10 is "\r", indicating a new line
            if(b1 != 13 && b1 != 10)
            {
                ("{0}",());
                (".");
            }
            else
            {
                ();
            }
        }
        ("\n");
// End reading the file in binary

// Close each object of the above new
        ();
        ();
        ();

// Read file attributes
// Print prompt information
("****************** Read file attributes******************************);

        FileInfo fiMyfile=new FileInfo("");
("File name: {0}",);
("File name (including path) : {0}",);
("File size (bytes): {0}",);
("File creation time: {0}",);
    }
}