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

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

我有一个TextBlock(名为“FlashText”)和两个Button(一个用于“上一个”button,另一个用于“下一个”button)。 我想要的是,当我点击“下一步”button时,TextBlock显示从指定行(例如,第一行)上的txt文件中读取的文本。 当我再次点击“下一步”时,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(); 

`

请帮忙。 谢谢一堆。


更新:

最近的主要代码是:

 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); } } } 

这是用于“ 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 } } 

运行解决scheme时出现错误消息: 尝试访问方法失败:System.IO.File.Exists(System.String)

我尝试过使用断点,而它正在获取LoadCard()方法,它直接抛出到构造函数的exception。 我已经重新检查了txtpath,但这是真的。

而且在' return _lines [_currentLine] '上点击'Next'/'Previous'button时也会出现错误信息 '行表示: ArgumentOutOfRangeException是未处理的 (如果点击“Next”的“Previous”button和GetNextLine()方法,它会在GetPreviousLine()方法上发生。

如果您需要更多信息,我很乐意提供。 🙂


更新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(); } } } 

我在上面标记的行上有错误: 字段'FCard.MainPage._lines'永远不会被分配给,并且将始终将其默认值为null

如果你想能够读取在文件中向前和向后移动的行,你需要将所有行存储在一个对象内(可能是一个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"); } 

你的加载文件可能看起来像这样:

  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; } 

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

  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]; } 

你的下一个按钮点击可能是这样的:

  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]; } } } 

你会想添加一些错误检查当然(如果文件丢失等)。

PS – 我已经编译这个代码使用一个文件,下面的行,并确认它的工作原理:

 Line one Line two Line three Line four 

更新:

如果你想要更类似于面向对象的方法,可以考虑创建一个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]; } } 

现在你可以在你的主表单中做这样的事情:

 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(); } } 

您可以将解析阶段与显示阶段分开。 首先,读取你的文件的每一行,并把它的字符串列表:

 List<string> list = new List<string>(); System.IO.StreamReader file = new System.IO.StreamReader(filePath); while(!file.EndOfStream) { string line = file.ReadLine(); list.Add(line); } Console.WriteLine("{0} lines read", list.Count); FlashText.Text = list[0]; 

然后,保留当前项目的ID并将其显示在您的块中。

 private int curId = 0; // on next button click if (curId < list.Count - 1) FlashText.Text = list[++curId]; // on prev button click if (curId > 0) FlashText.Text = list[--curId]; 

我喜欢现有的答案,但我认为创建一个类来表示一个对象列表是矫枉过正的这个问题。 我宁愿保持简单 – 一个字符串列表应该由List<string>

 public partial class Form1 : Form { private string path = @"D:\temp\test.txt"; private List<string> _lines; private int _currentLineIndex; public Form1() { InitializeComponent(); // if you're adding these using a reader then // you need to initialize the List first... _lines = new List<string>(); _lines = System.IO.File.ReadAllLines(path).ToList(); CurrentLineIndex = 0; } } 

三个简单的方法 – 一个处理Back单击,一个处理前向点击,一个更新标签。

  private void BackButton_Click(object sender, EventArgs e) { this.CurrentLineIndex--; } private void ForwardButton_Click(object sender, EventArgs e) { this.CurrentLineIndex++; } private void UpdateContentLabel() { this.ContentLabel.Text = _lines[CurrentLineIndex]; } 

并且当CurrentLineIndex属性被设置时,触发UpdateContentLabel()

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

使用此功能。 它适合我,希望它也可以帮助你

  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"; } 

然后使用拆分功能将其拆分到\n\r 。 这样你将得到文件的行。 将它们存储在一个数组或列表中。 然后请求下一个或上一个相应的索引。 在继续之前检查NULL