如何读取文本文件并将其显示在Visual Studio中的TextBlock(C#)

mrj*_*_05 10 c# windows parsing windows-phone-7

我是Visual Studio(C#)的新手.我想存储从文本文件中读取的文本并将其显示在TextBlock控件上,但仅用于指定的行.我怎样才能做到这一点?我试图在互联网上搜索,其中大多数只是显示阅读和写作的方式.

我有一个TextBlock(名为'FlashText')和两个Button(一个用于'Previous'按钮,另一个用于'Next'按钮).我想要的是,当我点击"下一步"按钮,然后TextBlock显示从指定行(例如,第一行)上的txt文件读取的文本.当我再次点击'Next'时,TextBlock应显示从文件中读取的第二行文本.

目的是制作一个简单的闪存卡.代码在这里:

`

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();
Run Code Online (Sandbox Code Playgroud)

`

请帮忙.谢谢一堆.


更新:

最近的主要代码是:

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 sender, RoutedEventArgs e)
    {
        DisplayNext();
    }

    private void DisplayNext()
    {
        try
        {
            FlashText.Text = _flashCard.GetNextLine();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void DisplayPrevious()
    {
        try
        {
            FlashText.Text = _flashCard.GetPreviousLine();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是针对" FlashCard " 课程的:

public class FlashCard
{
    private readonly string _file;
    private readonly List<string> _lines;

    private int _currentLine;

    public FlashCard(string file)
    {
        _file = file;
        _currentLine = -1;

        // Ensure the list is initialized
        _lines = new List<string>();

        try
        {
            LoadCard();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message); // This line got a message while running the solution
        }
    }

    private void LoadCard()
    {
        if (!File.Exists(_file))
        {
            // Throw a file not found exception
        }

        using (var reader = File.OpenText(_file))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                _lines.Add(line);
            }
        }
    }

    public string GetPreviousLine()
    {
        // Make sure we're not at the first line already
        if (_currentLine > 0)
        {
            _currentLine--;
        }

        return _lines[_currentLine]; //-- This line got an error
    }

    public string GetNextLine()
    {
        // Make sure we're not at the last line already
        if (_currentLine < _lines.Count - 1)
        {
            _currentLine++;
        }

        return _lines[_currentLine]; //-- This line got an error
    }
}
Run Code Online (Sandbox Code Playgroud)

我在运行解决方案时遇到错误消息:尝试访问该方法失败:System.IO.File.Exists(System.String).

我尝试过使用断点,当它获取LoadCard()方法时,它会直接抛到构造函数的异常上.我已经重新检查了txt路径,但这是真的.

我在点击' return _lines [_currentLine]上的'Next'/'Previous'按钮时也收到错误信息; '线表示:ArgumentOutOfRangeException是未处理的(如果击中它发生在GetPreviousLine()方法'上一个’按钮和用于GetNextLine()方法'下一步’.

如果您需要更多信息,我很乐意提供.:)


更新2

这是最近的代码:

public partial class MainPage : PhoneApplicationPage
{
    private string path = @"D:\My Workspaces\Windows Phone 7 Solution\FCard\EnglishFlashCard.txt";
    private List<string> _lines; //-- The error goes here
    private int _currentLineIndex;

    //private FlashCard _flashCard;

    // Constructor
    public MainPage()
    {
        InitializeComponent();
        //_lines = System.IO.File.ReadLines(path).ToList();

        if (File.Exists(path))
        {
            using (StreamReader sr = new StreamReader(path))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                    _lines.Add(line);
            }
        }

        CurrentLineIndex = 0;
    }

    private void btnLeft_Click(object sender, RoutedEventArgs e)
    {
        this.CurrentLineIndex--;
    }

    private void btnRight_Click(object sender, RoutedEventArgs e)
    {
        this.CurrentLineIndex++;
    }

    private void UpdateContentLabel()
    {
        this.FlashText.Text = _lines[CurrentLineIndex];
    }

    private int CurrentLineIndex
    {
        get {  return _currentLineIndex; }
        set
        {
            if (value < 0 || value >= _lines.Count) return;
            _currentLineIndex = value;
            UpdateContentLabel();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我在上面标记的行上有错误:字段'FCard.MainPage._lines'从未分配给,并且将始终将其默认值设置为null.

Jas*_*own 4

如果您希望能够读取文件中前后移动的行,您需要将所有行存储在对象(可能是一个List<string>或字符串数​​组)内,或者您必须通过手动重新定位光标方法Seek(例如FileStream.Seek)。这取决于闪存卡文件有多大。如果它非常大(包含很多行),您可能不想将其全部存储在内存中,而是更喜欢使用查找选项。

以下是加载闪存卡全部内容的示例:

namespace FlashReader
{
    public partial class Form1 : Form
    {
        // Hold your flash card lines in here
        private List<string> _lines;

        // Track your current line
        private int _currentLine;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // Load up your file
            LoadFile(@"D:\Path\To\EnglishFlashCard.txt");
        }
Run Code Online (Sandbox Code Playgroud)

您的加载文件可能如下所示:

        private void LoadFile(string file)
        {
            using (var reader = File.OpenText(file))
            {
                _lines = new List<string>();

                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    _lines.Add(line);
                }
            }

            // Set this to -1 so your first push of next sets the current
            // line to 0 (first element in the array)
            _currentLine = -1;
        }
Run Code Online (Sandbox Code Playgroud)

您之前的点击可能如下所示:

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            DisplayPrevious();
        }

        private void DisplayPrevious()
        {
            // Already at first line
            if (_currentLine == 0) return;

            _currentLine--;

            FlashText.Text = _lines[_currentLine];
        }
Run Code Online (Sandbox Code Playgroud)

您的下一次按钮单击可能如下所示:

        private void btnNext_Click(object sender, EventArgs e)
        {
            DisplayNext();
        }

        private void DisplayNext()
        {
            // Already at last line
            if (_currentLine == _lines.Count - 1) return;

            _currentLine++;

            FlashText.Text = _lines[_currentLine];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当然,您需要添加一些错误检查(如果文件丢失怎么办等)。

PS - 我已使用包含以下几行的文件编译了此代码,并确认其有效:

Line one 
Line two 
Line three 
Line four
Run Code Online (Sandbox Code Playgroud)

更新:

如果您想采用更类似于面向对象的方法,请考虑创建 FlashCard 类。像这样的东西:

public class FlashCard
{
    private readonly string _file;
    private readonly List<string> _lines;

    private int _currentLine;

    public FlashCard(string file)
    {
        _file = file;
        _currentLine = -1;

        // Ensure the list is initialized
        _lines = new List<string>();

        try
        {
            LoadCard();
        }
        catch (Exception ex)
        {
            // either handle or throw some meaningful message that the card
            // could not be loaded.
        }
    }

    private void LoadCard()
    {
        if (!File.Exists(_file))
        {
            // Throw a file not found exception
        }

        using (var reader = File.OpenText(_file))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                _lines.Add(line);
            }
        }
    }

    public string GetPreviousLine()
    {
        // Make sure we're not at the first line already
        if (_currentLine > 0)
        {
            _currentLine--;
        }

        return _lines[_currentLine];
    }

    public string GetNextLine()
    {
        // Make sure we're not at the last line already
        if (_currentLine < _lines.Count - 1)
        {
            _currentLine++;
        }

        return _lines[_currentLine];
    }
}
Run Code Online (Sandbox Code Playgroud)

现在您可以在主窗体中执行类似的操作:

public partial class Form1 : Form
{
    private FlashCard _flashCard;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // This could go under somewhere like a load new flash card button or
        // menu option etc.
        try
        {
            _flashCard = new FlashCard(@"c:\temp\EnglishFlashCard.txt");
        }
        catch (Exception)
        {
           // do something
        }
    }

    private void btnPrevious_Click(object sender, EventArgs e)
    {
        DisplayPrevious();
    }

    private void DisplayPrevious()
    {
        FlashText.Text = _flashCard.GetPreviousLine();
    }


    private void btnNext_Click(object sender, EventArgs e)
    {
        DisplayNext();
    }

    private void DisplayNext()
    {
        FlashText.Text = _flashCard.GetNextLine();
    }
}
Run Code Online (Sandbox Code Playgroud)