Alex Rivera | Logout

How Read a Text File and Display it onto a TextBlock in Visual Studio (C#)

Asked 2011-08-17T00:48:47.337
10

I am a newbie in Visual Studio (C#). I want to store a text read from a text file and display it on a TextBlock control, but just for a specified row. How can I do that? I've try to search on the internet, and most of them just show the way to read and write.

I have one TextBlock (named 'FlashText'), and two Button (one for the 'Previous' button, another one is for the 'Next' button). What I want is, when I hit the 'Next' button, then the TextBlock showing a text read from a txt file on a specified row (for instance, the first row). And when I hit the 'Next' again, then the TextBlock should be show the second row text read from the file.

The purpose is to make a simple flash card. The code is here:

`

private void btnRight_Click(object sender, RoutedEventArgs e) { 
  string filePath = @"D:\My Workspaces\Windows Phone 7 Solution\SimpleFlashCard\EnglishFlashCard.txt"; 
  int counter = 0;
  string line; 
  System.IO.StreamReader file = new System.IO.StreamReader(filePath); 
  while((line = file.ReadLine()) != null) { 
    Console.WriteLine(line); 
    counter++; 
  } 
} 

file.Close(); 
FlashText.Text = Console.ReadLine();

`

Please help. Thanks a bunch.


UPDATE:

Recently the main code is:

public partial class MainPage : PhoneApplicationPage
{
    private FlashCard _flashCard;

    // Constructor
    public MainPage()
    {
        InitializeComponent();

        // This could go under somewhere like a load new flash card button or
        // menu option etc.
        try
        {
            _flashCard = new FlashCard(@"D:\My Workspaces\Windows Phone 7 Solution\FCard\MyDocuments\EnglishFlashCard.txt");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void btnLeft_Click(object sender, RoutedEventArgs e)
    {
        DisplayPrevious();
    }

    private void btnRight_Click(object 
Edit
Report

1 Answer

1

Use this function. It works for me, hope it helps you too

    private string ReadFile(string filePath)
    {
        //this verse is loaded for the first time so fill it from the text file
        var ResrouceStream = Application.GetResourceStream(new Uri(filePath, UriKind.Relative));
        if (ResrouceStream != null)
        {
            Stream myFileStream = ResrouceStream.Stream;
            if (myFileStream.CanRead)
            {
                StreamReader myStreamReader = new StreamReader(myFileStream);

                //read the content here
                return myStreamReader.ReadToEnd();
            }
        }
        return "NULL";
    }

Then use split function to split it on \n\r. In that way you will get the lines of the file. Store them in an array or list. Then call for the respective index on next or previous. Check for NULL before proceeding.

answered 2012-09-05T09:07:56.137

Your Answer