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

文章目录

  • 前言
  • 一、界面展示
  • 二、使用步骤
    • 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种方式


一、界面展示

C# WPF读取文本内容的7种方式_第1张图片

二、使用步骤

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");
        }
    }
}

你可能感兴趣的:(WPF,wpf,c#,microsoft)