Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Sign In with Facebook Sign In with Google Sign In with OpenID

Categories

We have migrated to a new platform! Please note that you will need to reset your password to log in (your credentials are still in-tact though). Please contact lee@programmersheaven.com if you have questions.
Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

Reading a text file one line at a time

ITAITA Posts: 463Member
At the top of my app I have a label control which will display a line of text. This will work like an ad-rotator but will only display text quotes. I want to list the quotes inside a text file e.g:

"Help yourself now"
"Get free now"
"Have a nice day"

... etc

When the user clicks on a button it will display the next quote. I've now idea how to do this. All I know is that I can use a FileStream object (fS) to access the Position property - this will give me the position of the stream (i.e. fS.Position) and I also know that I can get the length of the stream with the length property (i.e. fS.Length).

I think I should try and check how many lines are in the file but am unsure how to continue.

How can I complete the task? Please help. Many thanks.

ITA

Comments

  • ing_gigioing_gigio Posts: 31Member
    : At the top of my app I have a label control which will display a line of text. This will work like an ad-rotator but will only display text quotes. I want to list the quotes inside a text file e.g:
    :
    : "Help yourself now"
    : "Get free now"
    : "Have a nice day"
    :
    : ... etc
    :
    : When the user clicks on a button it will display the next quote. I've now idea how to do this. All I know is that I can use a FileStream object (fS) to access the Position property - this will give me the position of the stream (i.e. fS.Position) and I also know that I can get the length of the stream with the length property (i.e. fS.Length).
    :
    : I think I should try and check how many lines are in the file but am unsure how to continue.
    :
    : How can I complete the task? Please help. Many thanks.
    :
    : ITA
    :


    For my suggestion I will assume that u are the writer of the text file so that u can edit it the way that u prefer (and that will make the code work ;)

    U need to write a text file as u would normally do BUT in the end of every message u should add an escape character. With this I mean a character u will never use on the message (here I used @, but remember u have all the unicode set to chose from :))

    2 important notes:

    1 .Peek() and .Read() returns an int... so u have to do the cast explicitely
    2 for the way the code is written u have to add the escape char also at the end of the last line

    the following code (it will works if u compile it) will read a file, parse the stream and add the messages in the correct position.
    For quickness here I used a fixed size array (I imagine u know the exact number of messages to store). In case..u can use a dynamic collection.


    [code]
    using System;
    using System.IO;

    public class ManageAdRotator
    {
    // the array where u can record the messages
    private string[] zMessage;
    private int i;

    public ManageAdRotator()
    {
    i = 0;
    zMessage = new string[10];
    }


    public void ShowNextAd()
    {
    // this should be put in a try&catch to be sure u don't throw
    // an unwanted exception in case the file cannot be found or
    // opened
    using (StreamReader sr = new StreamReader("Text.txt"))
    {

    // with peek() u look at the following char without "taking it"

    // here we will parse all the stream untill the end (char 0)
    while (sr.Peek() >= 0)
    {
    // the first read if for not reading @
    // the 2 following ones are for not recording in the string
    // the carry and end of line char
    if (sr.Peek() == 64) // 64 == @
    {

    // a test line to be sure the application works
    Console.WriteLine(zMessage[i]);
    // we found the escape char, so we say the prog to begin
    // a new message
    i++;
    // this is to skip the @ char and not store it in the
    // array
    sr.Read();
    // so u skip the end of line and carry chars
    sr.Read(); sr.Read();
    }

    // if everything is ok, u append the next char on the
    // appropriate message string
    else
    {
    zMessage[i] = zMessage[i] + (char)sr.Read();
    }
    }
    }
    }
    }

    public class Starter
    {
    public static void Main()
    {
    ManageAdRotator zManage = new ManageAdRotator();
    zManage.ShowNextAd();
    }
    }
    [/code]


    I hope this is what u need.
  • ITAITA Posts: 463Member
    The code works and completes the task! I do not want to read the whole file at once though - the prog does this and simply lists the contents of the file (which I can already do).

    I probably didn't explain it well enough - when the user clicks a button it will read one line of the file (the first one) and then display it. Then when (and only when) the button is clicked again it will display the second line of the file. Then again when the button is clicked (and only when it is clicked) the next line will be displayed and so on.

    I tried putting the code from the Main() function into the button event handler but it didn't work. I think I should remove the string array (which holds multiple messages) and replace it with just a string (which will then only hold one line of the file).

    What do you think?

    Please help (again). Many thanks.

    ITA
  • ing_gigioing_gigio Posts: 31Member
    : The code works and completes the task! I do not want to read the whole file at once though - the prog does this and simply lists the contents of the file (which I can already do).
    :
    : I probably didn't explain it well enough - when the user clicks a button it will read one line of the file (the first one) and then display it. Then when (and only when) the button is clicked again it will display the second line of the file. Then again when the button is clicked (and only when it is clicked) the next line will be displayed and so on.


    If I have to be honest...u have been clear enough and I caught well ur words.. But I preferred developping this idea 'cause of some things..
    When u load a file...u need to go on the bus...and this is not really performing..
    Now..if u have a short file to read...I think U shouldn't be afraid it to employ too much space... As long as I think mine was the easiest way to accomplish ur goal... why not to choose it? :)
    Let's suppose instead that u have a very long text file (but I think no pure text file can be longer than a couple megas..). A long file usually means that u have to frequently get access to it..and this means..a heavy usage of the bus (with a complex slowing of the system..with possible congestion), a higher possibility of error (even if it still remains very low) and an increased possibility to damage ur disk (and I don't think u would like to have ur machine blocked for hours..or days..and maybe all ur datas lost..).
    Moreover..consider this. My idea implies a higher memory usage...urs performance degradations. To better choose which one to prefer...go to a PC seller pricelist and check the cost of 512Mb of RAM and the one of a CPU upgrade and of Scsi harddisks


    Anyway, I don't want to be fixec on my ideas...if u have chosen that solution...it means that probably it's the best in ur case (just consider my point of view too, maybe it could be helpfull ;)

    I think ur task can be accomplished in 2 main ways.

    The first one: rearrange the code I suggested u last time. But now..as u said, u use just a string to store the line to display and have a new variable in which u store the number of the line just read(optional).
    How can u find the wanted line on the text file? As a separator char, use this combination "@XXXX@".
    Ur app will have to do this:
    1 - go and check for the first @ it finds in the textfile (the same thing it did with last time code)
    2 - store all the following chars untill u find the closing @. They will tell u the number associated to the line (in our case...the XXXXs)
    With this simple algorythm u can choose whicever line u want in the textfile, u are not bound to a sequential display (even if u are still forced to do a sequential parsing on the file to find the wanted line...).


    The second one: use the FileStream.Position property. It returns u a long and allows u to set and get the position of the cursor in a FileStream.
    this is what u can do with it: (let's assume u still have to display the first line)

    1 - begin reading the stream untill u find a remarker (@ can go in this case too)
    2 - once found @, stop the reading, record the position with a line like
    (Fs is ur filestream)

    long LastPosition = Fs.Position;

    3 - display ur string
    4 - ur app do some stuff..
    5 - now u have to display another line... so.. open the file once again
    6 - set the position which u have to start from

    Fs.Position = LastPosition;

    7 - read the stream and go to point 2

    A variation on this theme could be:
    write the text file so that u save exatly...let's say...100 chars for every message (no matter if u fill the space with really usefull chars or just blank ones).
    Wanna read the the N-th line?
    u just need to set the position in the stream

    Fs.Position = N * 100;


    I think u should write ur code out alone.. I just have few doubts on the position property..(how it works exactly if u don't close the stream???), but anything should be ok if every time u remember to open and close ur files.

    In case u need some other help...just ask me and I'll try to post the complete code as soon as possible

    Hughz!
  • koticsekoticse Posts: 17Member
    Hi,

    My suggestion is to use StreamReader class which help you read a line from the file.

    --koti.
  • ITAITA Posts: 463Member
    Thanks a million,

    ITA

    :-)

  • ing_gigioing_gigio Posts: 31Member
    : Hi,
    :
    : My suggestion is to use StreamReader class which help you read a line from the file.
    :
    : --koti.
    :
    It's a great idea but I discarded it for a simple reason: what if u have a message longer than a single line? Of course u can find some ways to make it work...but it would look more like a patch than an elegant solution.
    Anyway, if u just have to display one-line message...probably ur solution is the best one: easy and efficient

    Thx Koti
Sign In or Register to comment.