Almacenar Y Leer Datos Personales En Un Archivo Binario En C#

Este programa solicita al usuario su nombre, edad (como byte) y año de nacimiento (como entero). Los datos se almacenan en un archivo binario. El programa también incluye un lector para comprobar que los datos se han escrito correctamente y que pueden leerse correctamente. Este ejercicio demuestra cómo usar la serialización binaria y el manejo de archivos en C#. Los datos se guardarán en un formato estructurado, lo que permitirá su posterior lectura para su validación.

Grupo

Manejo de archivos en C#

Objectivo

1. El programa solicita al usuario que introduzca su nombre (como cadena), edad (como byte) y año de nacimiento (como entero).
2. Estos datos se almacenan en un archivo binario llamado personalData.dat.
3. El programa leerá el archivo binario para comprobar que los datos se hayan almacenado correctamente y mostrará su contenido al usuario.
4. Si el programa se ejecuta correctamente, confirmará que los datos se escribieron y leyeron correctamente.

Cree un programa que solicite al usuario su nombre, edad (byte) y año de nacimiento (int) y los almacene en un archivo binario. Cree también un lector para comprobar que los datos se hayan almacenado correctamente.

Ejemplo de ejercicio en C#

 Copiar código C#
using System;
using System.IO;

class PersonalData
{
    // Fields to store the user's data
    public string Name { get; set; }
    public byte Age { get; set; }
    public int YearOfBirth { get; set; }

    // Method to store the data in a binary file
    public void SaveToFile(string fileName)
    {
        // Create a new FileStream to open the file in write mode
        using (BinaryWriter writer = new BinaryWriter(File.Open(fileName, FileMode.Create)))
        {
            // Write the user's name (string length + actual string)
            writer.Write(Name.Length);  // Write the length of the string
            writer.Write(Name);  // Write the string itself

            // Write the age and year of birth
            writer.Write(Age);
            writer.Write(YearOfBirth);
        }
    }

    // Method to read the data from the binary file and display it
    public static PersonalData ReadFromFile(string fileName)
    {
        // Create a new instance of PersonalData to hold the read values
        PersonalData data = new PersonalData();

        // Open the file in read mode
        using (BinaryReader reader = new BinaryReader(File.Open(fileName, FileMode.Open)))
        {
            // Read the name (first read the length, then the actual string)
            int nameLength = reader.ReadInt32();  // Read the string length
            data.Name = new string(reader.ReadChars(nameLength));  // Read the string

            // Read the age and year of birth
            data.Age = reader.ReadByte();
            data.YearOfBirth = reader.ReadInt32();
        }

        return data;  // Return the PersonalData object with the read values
    }
}

class Program
{
    static void Main()
    {
        // Prompt the user for their name, age, and year of birth
        Console.Write("Enter your name: ");
        string name = Console.ReadLine();

        Console.Write("Enter your age: ");
        byte age = byte.Parse(Console.ReadLine());  // Parse the age as a byte

        Console.Write("Enter your year of birth: ");
        int yearOfBirth = int.Parse(Console.ReadLine());  // Parse the year of birth as an int

        // Create an instance of PersonalData and set the values
        PersonalData userData = new PersonalData
        {
            Name = name,
            Age = age,
            YearOfBirth = yearOfBirth
        };

        // Define the file name to store the data
        string fileName = "personalData.dat";

        // Save the data to the file
        userData.SaveToFile(fileName);

        // Read the data back from the file
        PersonalData readData = PersonalData.ReadFromFile(fileName);

        // Display the read data to the user
        Console.WriteLine("\nData read from file:");
        Console.WriteLine($"Name: {readData.Name}");
        Console.WriteLine($"Age: {readData.Age}");
        Console.WriteLine($"Year of Birth: {readData.YearOfBirth}");
    }
}

 Output

Enter your name: John Doe
Enter your age: 25
Enter your year of birth: 1996

Data read from file:
Name: John Doe
Age: 25
Year of Birth: 1996

Comparte este ejercicio de C#