从文本文件中读取和分离数据

时间:2015-03-04 19:48:30

标签: c#

我在尝试弄清楚如何阅读文本文件中的每一行时遇到了一些问题。文本文件用于存储书籍,歌曲和电影等媒体对象。每个媒体都有标题,年份,作者/艺术家,有些还有以rot13编码的摘要。我可以读取以BOOK,SONG,MOVIE开头的行,并使用if语句读取这些行并根据媒体类型将内容放入数组中但我不确定如何将摘要与媒体类型一起使用因为它不读取每一行,因为我没有if语句来检查不以媒体类型开头的行。文本文件和C#代码如下:

DATA.TXT:

  

BOOK | The Ring of the Ring | 1954 | J.R.R。托尔金

     

Fnheba,gur Qnex Ybeq,unf tngurerq gb uvz nyy gur Evatf bs Cbjre rkpr​​cg 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 |让我飞向月球| 1964年|不妨摆动| Frank Sinatra


  

MOVIE |公主新娘| 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。古尔fgbel VFÑ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。

C#脚本:

FileStream mediaFile = new FileStream("Data.txt", FileMode.Open, FileAccess.Read);
StreamReader mediaData = new StreamReader(mediaFile);

string mediaRow; // temporary variable to hold the string data for each row

while ((mediaRow = mediaData.ReadLine()) != null) // as long as there is more string data, the loop while continue
{
    if (mediaRow.StartsWith("BOOK"))
    {
        string[] dataSplit = mediaRow.Split('|');

        int year = 0;

        bool didConvert = Int32.TryParse(dataSplit[2].Trim(), out year);

        if (!didConvert)
        {
            Console.WriteLine("Year conversion error");
            Environment.Exit(0);
        }

        books[bookCount] = new Book(dataSplit[1].Trim(), year, dataSplit[3].Trim());
        media[mediaCount] = books[bookCount];

        bookCount++;
        mediaCount++;
    }
    else if (mediaRow.StartsWith("SONG"))
    {
        string[] dataSplit = mediaRow.Split('|');

        int year = 0;

        bool didConvert = Int32.TryParse(dataSplit[2].Trim(), out year);

        if (!didConvert)
        {
            Console.WriteLine("Year conversion error");
            Environment.Exit(0);
        }

        songs[songCount] = new Song(dataSplit[1].Trim(), year, dataSplit[3].Trim(), dataSplit[4].Trim());
        media[mediaCount] = songs[songCount];

        songCount++;
        mediaCount++;
    }
    else if (mediaRow.StartsWith("MOVIE"))
    {
        string[] dataSplit = mediaRow.Split('|');

        int year = 0;

        bool didConvert = Int32.TryParse(dataSplit[2].Trim(), out year);

        if (!didConvert)
        {
            Console.WriteLine("Year conversion error");
            Environment.Exit(0);
        }

        movies[movieCount] = new Movie(dataSplit[1].Trim(), year, dataSplit[3].Trim());
        media[mediaCount] = movies[movieCount];

        movieCount++;
        mediaCount++;
    }
}

1 个答案:

答案 0 :(得分:1)

假设MovieSongBook都在共享一些media数组的公共基类(让我们猜测它叫Media) 。您只需跟踪正在处理的Media实例。所以,像:

Media currentItem = null;
while ((mediaRow = mediaData.ReadLine()) != null) // as long as there is more string data, the loop while continue
{
     if (mediaRow.StartsWith("BOOK"))
     {
         // Do you book processing...
         books[bookCount] = new Book(dataSplit[1].Trim(), year, dataSplit[3].Trim());
         currentItem = books[bookCount];
         // ....
     }
     else if (mediaRow.StartsWith("SONG"))
     {
         // Do song processing
     } 
     else if (mediaRow.StartsWith("MOVIE"))
     {
         // Do movie processing
     }
     else
     {
         // this must be a summary for the previous item
         // assuming Media has a summary property:
         currentItem.Summary = mediaRow;
     }
}