gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 12:41:34 27 4
gpt4 key购买 nike

我是 Visual Studio (C#) 的新手。我想存储从文本文件读取的文本并将其显示在 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();

`

请帮忙。非常感谢。


更新:

最近主要代码是:

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 未处理(如果点击“上一个”按钮和“下一个”按钮的 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();
}
}

关于c# - 如何读取文本文件并将其显示到 Visual Studio (C#) 中的 TextBlock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7086829/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com