C# WPF读取文本内容的7种方式

news/2024/10/19 23:30:10/

文章目录

  • 前言
  • 一、界面展示
  • 二、使用步骤
    • 1.引入库
    • 2.界面代码
    • 3.后台代码
      • (1)打开文件
      • (2)第一种:基于FileStream,并结合它的Read方法读取指定的字节数组,最后转换成字符串进行显示。
      • (3)第二种:基于FileStream,一个字节一个字节读取,放到字节数组中,最后转换成字符串进行显示。
      • (4)第三种:基于File类,直接全部读取出来并显示。
      • (5)第四种:基于StreamReader类,一行一行读取,最后拼接并显示。
      • (6) 第五种:基于StreamReader类,一次读到结尾,最后显示
      • (7)第六种:基于StreamReader类,一行一行读取,通过EndOfStream判断是否到结尾,最后拼接并显示
      • (8)第七种:基于FileStream和 StreamReader类来实现
      • (9)打印代码
      • (10)System 扩展方法


前言

C#读取文本内容的7种方式


一、界面展示

在这里插入图片描述

二、使用步骤

1.引入库

代码如下(示例):

using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using static System.Net.Mime.MediaTypeNames;

2.界面代码

代码如下(示例):

<Window x:Class="ReadFileDemo.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:ReadFileDemo"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"><Grid><Grid.ColumnDefinitions><ColumnDefinition Width="100"/><ColumnDefinition/></Grid.ColumnDefinitions><Grid.RowDefinitions><RowDefinition/><RowDefinition/><RowDefinition/><RowDefinition/><RowDefinition/><RowDefinition/><RowDefinition/><RowDefinition/><RowDefinition/><RowDefinition/></Grid.RowDefinitions><Label Grid.Row="0" Grid.Column="0" Content="选择文件" VerticalAlignment="Center" HorizontalAlignment="Center"></Label><TextBox Grid.Row="0" Grid.Column="1" x:Name="tbFileName" Text="C:\Users\beango.cheng\Desktop\Barcode系统.txt" VerticalContentAlignment="Center" VerticalAlignment="Center" Height="30" Margin="10 0 80 0"></TextBox><Button Grid.Row="0" Grid.Column="1" VerticalAlignment="Center" HorizontalAlignment="Right" Width="60" Height="30" Margin="5" Content="选择" Click="SelectButton_OnClick"></Button><RichTextBox Grid.Row="1" Grid.Column="1" Grid.RowSpan="10" Name="txtRichTextBox" Margin="10 5 5 5"></RichTextBox>       <Button Grid.Row="1" Grid.Column="0"  Margin="10 5" Content="第一种方式" Click="ReadFileButton1_OnClick"></Button><Button Grid.Row="2" Grid.Column="0"  Margin="10 5" Content="第二种方式" Click="ReadFileButton2_OnClick"></Button><Button Grid.Row="3" Grid.Column="0"  Margin="10 5" Content="第三种方式" Click="ReadFileButton3_OnClick"></Button><Button Grid.Row="4" Grid.Column="0"  Margin="10 5" Content="第四种方式" Click="ReadFileButton4_OnClick"></Button><Button Grid.Row="5" Grid.Column="0"  Margin="10 5" Content="第五种方式" Click="ReadFileButton5_OnClick"></Button><Button Grid.Row="6" Grid.Column="0"  Margin="10 5" Content="第六种方式" Click="ReadFileButton6_OnClick"></Button><Button Grid.Row="7" Grid.Column="0"  Margin="10 5" Content="第七种方式" Click="ReadFileButton7_OnClick"></Button></Grid>
</Window>

3.后台代码

(1)打开文件

		private void SelectButton_OnClick(object sender, RoutedEventArgs e){this.txtRichTextBox.Document.Blocks.Clear();AppendTestData("选择文件", MyBrushes.PASS);OpenFileDialog openFileDialog = new OpenFileDialog();openFileDialog.Title = "选择文件";openFileDialog.Multiselect = false;//选择多个文件openFileDialog.RestoreDirectory = true;//跟踪上次打开的文件的目录openFileDialog.Filter = "Text files(*.txt) | *.txt";if (openFileDialog.ShowDialog() == true){tbFileName.Text = openFileDialog.FileName;}}

(2)第一种:基于FileStream,并结合它的Read方法读取指定的字节数组,最后转换成字符串进行显示。

    private void ReadFileButton1_OnClick(object sender, RoutedEventArgs e){this.txtRichTextBox.Document.Blocks.Clear();AppendTestData("第一种:基于FileStream,并结合它的Read方法读取指定的字节数组,最后转换成字符串进行显示。", MyBrushes.Yellow);FileStream fs = new FileStream(this.tbFileName.Text, FileMode.Open, FileAccess.Read);int n = (int)fs.Length;byte[] b = new byte[n];int r = fs.Read(b, 0, n);fs.Close();string txtFileContent = Encoding.UTF8.GetString(b, 0, n);AppendTestData(txtFileContent, MyBrushes.Green);}

(3)第二种:基于FileStream,一个字节一个字节读取,放到字节数组中,最后转换成字符串进行显示。

	private void ReadFileButton2_OnClick(object sender, RoutedEventArgs e){this.txtRichTextBox.Document.Blocks.Clear();AppendTestData("第二种:基于FileStream,一个字节一个字节读取,放到字节数组中,最后转换成字符串进行显示。", MyBrushes.Yellow);FileStream fs = new FileStream(this.tbFileName.Text, FileMode.Open, FileAccess.Read);long n = fs.Length;byte[] b = new byte[n];int data, index;index = 0;data = fs.ReadByte();while (data != -1){b[index++] = Convert.ToByte(data);data = fs.ReadByte();}fs.Close();string txtFileContent = Encoding.UTF8.GetString(b);AppendTestData(txtFileContent, MyBrushes.Green);}

(4)第三种:基于File类,直接全部读取出来并显示。

	private void ReadFileButton3_OnClick(object sender, RoutedEventArgs e){this.txtRichTextBox.Document.Blocks.Clear();AppendTestData("第三种:基于File类,直接全部读取出来并显示。", MyBrushes.Yellow);string txtFileContent = System.IO.File.ReadAllText(tbFileName.Text);AppendTestData(txtFileContent, MyBrushes.Green);}

(5)第四种:基于StreamReader类,一行一行读取,最后拼接并显示。

 	private void ReadFileButton4_OnClick(object sender, RoutedEventArgs e){this.txtRichTextBox.Document.Blocks.Clear();AppendTestData("第四种:基于StreamReader类,一行一行读取,最后拼接并显示。", MyBrushes.Yellow);StreamReader sr = new StreamReader(this.tbFileName.Text, Encoding.UTF8);string line = sr.ReadLine();while (line != null){AppendTestData(line, MyBrushes.Green);line = sr.ReadLine();//if (line != null)//{//    this.rtb_Content.AppendText("\r\n");//}}sr.Close();}

(6) 第五种:基于StreamReader类,一次读到结尾,最后显示

  	private void ReadFileButton5_OnClick(object sender, RoutedEventArgs e){this.txtRichTextBox.Document.Blocks.Clear();AppendTestData("第五种:基于StreamReader类,一次读到结尾,最后显示。", MyBrushes.Yellow);StreamReader sr = new StreamReader(this.tbFileName.Text, Encoding.UTF8);string txtFileContent = sr.ReadToEnd();sr.Close();AppendTestData(txtFileContent, MyBrushes.Green);}

(7)第六种:基于StreamReader类,一行一行读取,通过EndOfStream判断是否到结尾,最后拼接并显示

 private void ReadFileButton6_OnClick(object sender, RoutedEventArgs e){this.txtRichTextBox.Document.Blocks.Clear();AppendTestData("第六种:基于StreamReader类,一行一行读取,通过EndOfStream判断是否到结尾,最后拼接并显示。", MyBrushes.Yellow);StreamReader sr = new StreamReader(this.tbFileName.Text, Encoding.UTF8);//while (!sr.EndOfStream)//{//    AppendTestData(sr.ReadLine(),MyBrushes.Green);//}string txtFileContent = string.Empty;while (!sr.EndOfStream){txtFileContent += sr.ReadLine();if (!sr.EndOfStream){txtFileContent += "\r\n";}}sr.Close();AppendTestData(txtFileContent, MyBrushes.Green);}

(8)第七种:基于FileStream和 StreamReader类来实现

 private void ReadFileButton7_OnClick(object sender, RoutedEventArgs e){this.txtRichTextBox.Document.Blocks.Clear();AppendTestData("第七种:基于FileStream和 StreamReader类来实现。", MyBrushes.Yellow);FileStream fs = new FileStream(this.tbFileName.Text, FileMode.Open, FileAccess.Read);StreamReader sr = new StreamReader(fs, Encoding.UTF8);string txtFileContent = sr.ReadToEnd();fs.Close();sr.Close();AppendTestData(txtFileContent, MyBrushes.Green);}

(9)打印代码

	public enum MyBrushes : uint{Black = 0xFF000000,White = 0xFFFFFFFF,Red = 0xFFBF1818,Green = 0xFF28B028,Blue = 0xFF2880D8,Yellow = 0xFFD8B628,IDLE = 0x88237380,PASS = 0x882DB96D,FAIL = 0x88CB1111,TESTING = 0x88876918,RichBlue = 0xFF0098FF,RichGreen = 0xFF1ACB62,RichRed = 0xFFFB4B4B,RichYellow = 0xFFEE9617}
	private Block AppendTestData(string data,MyBrushes myBrushes){Block block = null;if(this.Dispatcher.Thread == System.Threading.Thread.CurrentThread){block = GetBlock(data, myBrushes);this.txtRichTextBox.Document.Blocks.Add(block);}else{this.Dispatcher.Invoke((Action)delegate{block = AppendTestData(data, myBrushes);});}return block;}private Block GetBlock(string data,MyBrushes myBrushes){Inline inline = new Run(data);inline.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(myBrushes.ToBrushString()));return new Paragraph(inline){LineHeight = 1.0};}

(10)System 扩展方法

namespace System
{public static partial class ExpandClass{public static string ToBrushString(this Enum e){return "#" + Convert.ToUInt32(e).ToString("X2");}}
}

http://www.ppmy.cn/news/239807.html

相关文章

lex yacc flex bison

简介 lex与yacc是两个在Unix下的分别作词法分析和语法分析的工具&#xff0c; Linux对应flex与bison。 Yacc 与 Lex 快速入门 flex 和bison的安装和使用 Windows下安装lex(flex)与yacc(bison)

CS61B - Lec 8 - Interface inheritance

Lec8 - Inheritance 1 Lec8 - Inheritance 1Is an && Has an步骤Overriding vs OverloadingInterface inheritanceImplementation inheritanceStatic and dynamic type(重点&#xff09; Lec8 - Inheritance 1 本章源于一个问题 public static String longest(SLList…

026FLEX

flex布局 CSS3弹性盒子(Flexible Box或Flexbex)&#xff0c;是一种用于在页面上布置元素的布局模式&#xff0c;使得当页面布局必须适应不同的屏幕尺寸和不同的显示设备时&#xff0c;元素可预测地运行/列。对于许多应用程序&#xff0c;弹性盒子模型提供了对块模型的改进&…

LEXSTR

题目链接&#xff1a;http://www.spoj.com/problems/LEXSTR/ 题意是给一个字符串str&#xff0c;然后给出m个数对 i , j&#xff1b; 代表str[i] 和 str[j] 可以互相之间交换任意次 &#xff0c;然后问如何交换使得这个字符串的字典序最小&#xff0c;输出这个字典序最小的字符…

CS61B - Lec 21 - Binary Search Tree

Lec 21 - BST Binary Search Trees概念查找插入删除 从Lec20开始&#xff0c;就转战CS61B Spring 2019了&#xff0c;18后面全变成公开课了。 本章主要讲的是Binary Search Tree&#xff0c;是一种非常流行的数据结构&#xff0c;据说各大面试中都会出现。其中用到了超多的recu…

Lex正则表达式

字符 解释 . 匹配除换行符("/n")以外的任何单个字符 * 匹配前面表达式的零个或多个拷贝 [] 匹配括号中的任意的字符类 ^ 作为正则表达式的第一个字符匹配行的开头 $ 作为正则表达式的最后一个字符匹配行的结尾 {} …

lex yacc

http://www.linuxdiyf.com/viewarticle.php?id91568 作者&#xff1a;绚丽也尘埃 最近看《GCC-the-Complete-Reference-fly》才知道有lex和yacc这两个有趣的工具&#xff0c;并且fedora core 8也默认安装有这两个工具&#xff0c;所以趁此机会学习一下&#xff0c;以前学编译…

lex与yacc之lex符号表示例

在lex初探篇中&#xff0c;每次要定义新的单词&#xff0c;都需要重新编译&#xff0c;这是非常麻烦的。但是如果在词法分析程序运行时能够构建一个单词表&#xff0c;那么就可以在 添加新的单词时不用修改和重新编译lex程序。symboltable.l%{/** Word recognizer with a symbo…