0

Hey I need to read info from a textfile.

Data.txt file

By the way there are different data types I have solved how to format SONG properly but not Movie or Book.

This is the text file, from this I am having troubles feeding it too my constructer.

        public Movie(string type, string title, int year, string director, string summary) : base(title, year)
    {
        Type = type;
        Title = title;
        Year = year;
        Director = director;
        Summary = summary;
    }

Currently for code I have.

Movie currentMovie = new Movie(strArray[0], strArray[1], Convert.ToInt32(strArray[2]), strArray[3], strArray[4]);

movies.Add(currentMovie);

Console.WriteLine(currentMovie);

I can not figure out how to input the data from the textfile into this constructer. I am using this as as a split command.. strArray = str.Split(new Char[] { '|', '\n', '\t' });

I am mainly asking for a way to format from the place after the fourth variable. As to the beginning of the Summary.

Here's an example from my source data:

BOOK|The Fellowship of the Ring|1954|J.R.R. Tolkien
Fnheba, gur Qnex Ybeq, unf tngurerq gb uvz nyy gur Evatf bs Cbjre rkprcg bar - gur Bar Evat gung ehyrf gurz nyy - juvpu unf snyyra vagb gur unaqf bs gur uboovg Ovyob Onttvaf. Lbhat Sebqb Onttvaf svaqf uvzfrys snprq jvgu na vzzrafr gnfx jura Ovyob ragehfgf gur Evat gb uvf pner. Sebqb zhfg znxr n crevybhf wbhearl npebff Zvqqyr-rnegu gb gur Penpxf bs Qbbz, gurer gb qrfgebl gur Evat naq sbvy gur Qnex Ybeq va uvf rivy checbfr.
-----
SONG|Fly Me to the Moon|1964|It Might as Well be Swing|Frank Sinatra
-----
MOVIE|The Princess Bride|1987|Rob Reiner
N xvaqyl tenaqsngure fvgf qbja jvgu uvf tenaqfba naq ernqf uvz n orqgvzr fgbel. Gur fgbel vf bar gung unf orra cnffrq qbja guebhtu sebz sngure gb fba sbe trarengvbaf. Nf gur tenaqsngure ernqf gur fgbel, gur npgvba pbzrf nyvir. Gur fgbel vf n pynffvp gnyr bs ybir naq nqiragher nf gur ornhgvshy Ohggrephc vf xvqanccrq naq uryq ntnvafg ure jvyy va beqre gb zneel gur bqvbhf Cevapr Uhzcreqvapx, naq Jrfgyrl (ure puvyqubbq ornh, abj erghearq nf gur Qernq Cvengr Eboregf) nggrzcgf gb fnir ure. Ba gur jnl ur zrrgf na nppbzcyvfurq fjbeqfzna naq n uhtr, fhcre fgebat tvnag, obgu bs jubz orpbzr uvf pbzcnavbaf va uvf dhrfg. Gurl zrrg n srj onq thlf nybat gur jnl gb erfphr Ohggrephc.
-----
BOOK|The Two Towers|1954|J.R.R. Tolkien
Gur Sryybjfuvc jnf fpnggrerq. Fbzr jrer oenpvat ubcryrffyl sbe jne ntnvafg gur napvrag rivy bs Fnheba. Fbzr jrer pbagraqvat jvgu gur gernpurel bs gur jvmneq Fnehzna. Bayl Sebqb naq Fnz jrer yrsg gb gnxr gur npphefrq Evat bs Cbjre gb or 

qrfgeblrq va Zbeqbe - gur qnex Xvatqbz jurer Fnheba jnf fhcerzr. Gurve thvqr jnf Tbyyhz, qrprvgshy naq yhfgsvyyrq, fynir gb gur pbeehcgvba bs gur Evat.

Thanks to this code I was able to achieve this.

if (strArray[0] == typeSONG) {
Song currentSong = new Song(strArray[0], strArray[1], Convert.ToInt32(strArray[2]), strArray[3], strArray[4]);

songs.Add(currentSong);

Console.WriteLine(currentSong);
}

enter image description here

My code in its entirety.

enter code here    class Program
{
    public string fileName = "F:\\Data.txt";

    public static void ReadData()
    {
        string fileName = "F:\\Data.txt";

        List<Song> songs = new List<Song>();

        List<Movie> movies = new List<Movie>();

        List<Book> books = new List<Book>();

        using (StreamReader sr = new StreamReader(fileName))
        {
            while (sr.Peek() >= 0)
            {
                string str;
                str = sr.ReadLine();

                string typeBOOK = "BOOK";
                string typeMOVIE = "MOVIE";
                string typeSONG = "SONG";

                var strArray = str.Split(new Char[] { '|' });
                
                if (strArray[0] == "MOVIE")
                {
                    int firstLine = strArray[3].IndexOf(Environment.NewLine);
                    string author = strArray[3].Substring(0, firstLine);
                    string summary = strArray[3].Substring(firstLine + 1).Trim();
                }
            }
        }
    }
    static void Main(string[] args)
    {
        ReadData();
    }
}

}

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Blocare
  • 11
  • 2

1 Answers1

0

This is a lot of code to type right into the reply window. There's probably several bugs.

// One class to rule them all, one class to find them
// One class to bring them all, and in the darkness bind them
public class Media
{
    public string Type {get;set;}
    public string Title {get;set;}
    public int Year {get;set;} 
    public string AuthorDirector {get;set;}
    public string Summary {get;set;}

    public override string ToString()
    {
        return $"{Type}|{Title}({Year}) by {AuthorDirector}";
    }
}

public class Program
{
    // first: a method to divide the file into separate records
    private IEnumerable<string> SeparateRecordStrings(string fileName, string recordDelimiter)
    {
        StringBuilder current = new StringBuilder();
        var lines = File.ReadLines(fileName);
        foreach(var line in lines)
        {
            if (line.StartsWith(recordDelimiter))
            {
                yield return current.ToString();
                current.Clear();
            }
            else 
            {
                current.AppendLine(line);
            }
        }
        if (current.Length > 0)
        {
            var final = current.ToString().Trim();
            if (!string.IsNullOrWhitespace(final))
            {
                yield return final;
            }
        }
    }
    
    // then use the prior method to handle individual record strings
    public IEnumerable<Media> ReadRecords(string fileName)
    {
        var records = SepearteRecordStrings(fileName, "-----");
    
        foreach(string record in records)
        {
            using (var reader new StringReader(record))
            {
                var fields = reader.ReadLine().Split("|"); //not really a fan of String.Split()
                var current = new Media() {
                    Type = fields[0],
                    Title = fields[1],
                    Year = int.Parse(fields[2])
                };

                switch(fields[0])
                {
                    case "SONG":
                         current.Summary = fields[3];
                         current.AuthorDirector = fields[4];
                         break;
                    case "BOOK":
                    case "MOVIE":
                        current.AuthorDirector = fields[3];
                        var summary = new StringBuider();
                        string line = null;
                        while ((line = reader.ReadLine()) != null)
                        {
                             summary.AppendLine(line);
                        }
                        current.Summary = summary.ToString();
                        break;
                }
                yield return current;
            }
        }
    }

    // and now the Main() method can be very short and easy to write.
    public static void Main(string[] args)
    {
        var records = ReadRecords("data.txt");

        var Movies = records.Where(r => r.Type == "MOVIE");
        var Books  = records.Where(r => r.Type == "BOOK");
        var Songs  = records.Where(r => r.Type == "SONG");

        Console.WriteLine(string.Join("\n", Movies));
    }
}

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794