Как читать текстовый файл и отображать его на TextBlock в Visual Studio (С#)
Я новичок в Visual Studio (С#). Я хочу сохранить текст, прочитанный из текстового файла, и отобразить его в элементе управления TextBlock, но только для указанной строки. Как я могу это сделать?
Я пытаюсь выполнить поиск в Интернете, и большинство из них просто показывают способ читать и писать.
У меня есть один TextBlock (с именем "FlashText" ) и две кнопки (одна для кнопки "Предыдущая" , другая для кнопки "Далее" ). Я хочу, когда я нажимаю кнопку "Далее" , а затем 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();
`
Пожалуйста, помогите. Спасибо, куча.
UPDATE:
В последнее время основной код:
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, но это правда.
И я также получил сообщение об ошибке, нажав кнопку "Далее" / "Предыдущая" на странице " return _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.
Ответы
Ответ 1
Если вы хотите читать строки, перемещающиеся назад и вперед в файле, вам нужно либо сохранить все строки внутри объекта (возможно, 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
UPDATE:
Если вы хотите пойти с чем-то более близким к объектно-ориентированному подходу, подумайте о создании класса 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();
}
}
Ответ 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];
Затем сохраните идентификатор текущего элемента и отобразите его в своем блоке.
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];
Ответ 3
Мне нравятся существующие ответы, но я думаю, что создание класса для представления списка объектов является излишним для этой проблемы. Я бы предпочел сохранить его простым: список строк должен быть представлен только 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();
}
}
Ответ 4
Используйте эту функцию. Это работает для меня, надеюсь, что это поможет вам.
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";
}
Затем используйте функцию split, чтобы разбить ее на \n\r
. Таким образом вы получите строки файла. Храните их в массиве или списке. Затем вызовите соответствующий индекс в следующем или предыдущем. Перед тем, как продолжить, проверьте NULL
.