¿Cómo usar BinaryReader en bucle para poder mostrar fragmentos de información en el formato correcto?

StackOverflow https://stackoverflow.com/questions/7830908

  •  27-10-2019
  •  | 
  •  

Pregunta

Estoy haciendo la tarea y llegué a la parte en la que necesito mostrar mis datos del archivo de datos. El problema es que puedo mostrar datos individuales usando BinaryReader () pero no puedo crear un ciclo correcto que muestre todos los datos en el formato especificado a continuación:

Enter Book Title: Title 1
Enter Author's First Name: First 1
Enter Author's Last Name: Last 1
Enter Publisher's Name: Publisher 1
Enter Book Price: $1.1
Would like to enter another book? [Y or N] y
Enter Book Title: Title 2
Enter Author's First Name: First 2
Enter Author's Last Name: Last 2
Enter Publisher's Name: Publisher 2
Enter Book Price: $2.2
Would like to enter another book? [Y or N] n

Title 1
Publisher 1
1.1
First 1 Last 1

Title 2
Publisher 2
2.2
First 2 Last 2

En cambio, solo estoy mostrando la última entrada. ¿Ves el problema? No sé cómo mostrar todos los datos de la carpeta de datos utilizando un bucle.

Agradezco cualquier consejo sobre cómo se podría hacer esto.

¡Gracias!

Aquí están mis archivos de código:

<×Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Lab_7
{
    class Program
    {
        private const string FILE_NAME = "lab07.dat";

        static void Main(string[] args)
        {
            char ask;

            if (!File.Exists(FILE_NAME))
            {
                FileStream fileStream = new FileStream(FILE_NAME, FileMode.OpenOrCreate);
            }

            Book book = new Book();

            FileStream writeStream = new FileStream(FILE_NAME, FileMode.Append);
            BinaryWriter write = new BinaryWriter(writeStream);

            do
            {
                Console.Write("Enter Book Title: ");
                book.Title = Console.ReadLine();
                Console.Write("Enter Author's First Name: ");
                book.AuthorFirstName = Console.ReadLine();
                Console.Write("Enter Author's Last Name: ");
                book.AuthorLastName = Console.ReadLine();
                Console.Write("Enter Publisher's Name: ");
                book.PublisherName = Console.ReadLine();
                Console.Write("Enter Book Price: $");
                book.Price = float.Parse(Console.ReadLine());
                Console.Write("Would like to enter another book? [Y or N] ");
                ask = char.Parse(Console.ReadLine().ToUpper());

                book.saveDataTo(write);
            }
            while (ask == char.Parse("Y"));

            write.Close();

            FileStream readStream = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
            BinaryReader read = new BinaryReader(readStream);

            book.display();

            read.Close();
        }
    }
}

<”Publication.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Lab_7
{
    class Publication
    {
        private float price;
        private string publisherName, title;

        public float Price
        {
            get
            {
                return price;
            }
            set
            {
                price = value;
            }
        }

        public string PublisherName
        {
            get
            {
                return publisherName;
            }
            set
            {
                publisherName = value;
            }
        }

        public string Title
        {
            get
            {
                return title;
            }
            set
            {
                title = value;
            }
        }

        public void display()
        {
            Console.WriteLine("{0}\n{1}\n{2}", title, publisherName, price);
        }
    }
}

<×Book.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Lab_7
{
    class Book : Publication
    {
        private string authorFirstName, authorLastName;

        public string AuthorFirstName
        {
            get
            {
                return authorFirstName;
            }
            set
            {
                authorFirstName = value;
            }
        }

        public string AuthorLastName
        {
            get
            {
                return authorLastName;
            }
            set
            {
                authorLastName = value;
            }
        }

        public new void display()
        {
            base.display();
            Console.WriteLine("{0}", getAuthorName());
        }

        public string getAuthorName()
        {
            return authorFirstName + " " + authorLastName;
        }

        public void readDataFrom(BinaryReader r)
        {

            base.Price = r.ReadSingle();
            base.PublisherName = r.ReadString();
            base.Title = r.ReadString();
            authorFirstName = r.ReadString();
            authorLastName = r.ReadString();
        }

        public void saveDataTo(BinaryWriter w)
        {
            w.Write(base.Price);
            w.Write(base.PublisherName);
            w.Write(base.Title);
            w.Write(AuthorFirstName);
            w.Write(AuthorLastName);
        }
    }
}

Gracias por la ayuda.

Saludos.

HelpNeeder.

- EDITAR -

¡Funciona! ¡Gracias!

    while (read.PeekChar() != -1)
    {
        book.readDataFrom(read);
        book.display();
    }

¡Además, tenía que asegurarme de que se creara un nuevo archivo cada vez que ejecutaba el programa!

Además, debo asegurarme de cerrar mi FileStreams porque sigo fallando el programa.

¿Fue útil?

Solución

Olvidas realizar un bucle.book.display solo muestra un libro.También te olvidas de leer los datos del libro.

Puede comprobar si hay más datos en el archivo echando un vistazo.Si peek devuelve -1, sabe que hayno más datos.

Ejemplo:

FileStream readStream = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
BinaryReader read = new BinaryReader(readStream);

while (read.PeekChar() != -1)
{
    book.readDataFrom(read);
    book.display();
}

Otros consejos

Utilice binaryReader.PeekChar () método.

while(binaryReader.PeekChar()!=-1)
{
//
}

EDITAR:

FileStream readStream = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
BinaryReader read = new BinaryReader(readStream);
Book book = new Book();
 while(read.PeekChar()!=-1)
    {
      book.readDataFrom(read);
      book.display();
    }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top