本文介绍了如何创建显示文本文件的应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 大家好,请帮我练习。我正在尝试在WPF中创建一个打开,读取和显示文本文件内容的应用程序,但它不想打开任何文本文件。我做错了什么? 以下是我一直在使用的代码: Hi all please help me with my exercise. I'm trying to create a application in WPF that open, read and display the contents of a text file, but it don't want to open any text files. What am I doing wrong?Here's the code that I've been using:namespace WhileStatement{ public partial class MainWindow : Window { private OpenFileDialog openFileDialog = null; public MainWindow() { InitializeComponent(); openFileDialog = new OpenFileDialog(); } private void openFileClick(object sender, RoutedEventArgs e) { openFileDialog.ShowDialog(); } private void openFileDialogFileOk(object sender, System.ComponentModel.CancelEventArgs e) { string fullPathname = openFileDialog.FileName; FileInfo src = new FileInfo(fullPathname); fileName.Text = src.FullName; TextReader reader = src.OpenText(); displayData(reader); } private void displayData(TextReader reader) { source.Text = ""; string line = reader.ReadLine(); while (line != null); { source.Text += line + '\n'; line = reader.ReadLine(); } reader.Close(); } }} 我尝试了什么: 我试过google和MSDN Library。What I have tried:I've tried google and MSDN Library.推荐答案 private void openFileClick(object sender, RoutedEventArgs e){ if(openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { System.IO.StreamReader sr = new System.IO.StreamReader(openFileDialog1.FileName); source.Text = sr.ReadToEnd(); sr.Close(); } } 此外,除了 wpf-tutorial .com [ ^ ]另一个有用的网站是:你应该知道的关于WPF的2000件事WPF开发人员需要知道的所有内容,在Bite-Sized Chunks中 [ ^ ] Also, besides wpf-tutorial.com[^] another good helpful site is: 2,000 Things You Should Know About WPF | Everything a WPF Developer Needs to Know, in Bite-Sized Chunks[^] public MainWindow(){ InitializeComponent(); openFileDialog = new OpenFileDialog(); openFileDialog.FileOk += openFileDialogFileOk; // <-- Add this line} 你还应该避免在循环中使用字符串连接,因为效率非常低: You should also avoid using string concatenation in a loop, as it's extremely inefficient:private void openFileDialogFileOk(object sender, System.ComponentModel.CancelEventArgs e){ string fullPathname = openFileDialog.FileName; FileInfo src = new FileInfo(fullPathname); fileName.Text = src.FullName; source.Text = File.ReadAllText(src.FullName);} File.ReadAllText方法 [ ^ ] 这篇关于如何创建显示文本文件的应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-19 07:11