我是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();
`
请帮忙。非常感谢。
更新
最近的主要代码是:
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
}
}
运行解决方案时出现错误消息:尝试访问方法失败:System.IO.File.Exists(System.String)。
我尝试过使用断点,当它获取LoadCard()方法时,它会直接抛到构造函数的异常上。我已经重新检查了txt路径,但确实如此。
我在点击'返回_lines [_currentLine]; '行上的'下一步'/'上一页'按钮时也收到错误消息: 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();
}
}
}
我在上面标记的行上有错误说明:字段'FCard.MainPage._lines'永远不会被分配给,并且总是将其默认值为null 。
答案 0 :(得分: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");
}
您的加载文件可能如下所示:
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();
}
}
答案 1 :(得分:2)
您可以将解析阶段与显示阶段分开。 首先,读取文件的每一行并列出其中的字符串:
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];
答案 2 :(得分:1)
我喜欢现有的答案,但我认为创建一个表示对象列表的类对于这个问题来说太过分了。我更喜欢保持简单 - 字符串列表应该由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;
}
}
三种简单方法 - 一种用于处理后退点击,一种用于处理前向点击,另一种用于更新标签。
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();
}
}
答案 3 :(得分:1)
使用此功能。它适用于我,希望它也可以帮助你
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
。