C#实现RTF文件的打开、保存、查找、查找下一个、替换、全部替换

软件:Visual Studio 2019

项目名:WindowsFormsApp12

一.窗体设计

从工具栏添加3个Label、3个TextBox、6个Button、1个RichTextBox(ScrollBars属性为ForcedVertical)到窗体中,如下图所示:

 二.代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp12
{
    public partial class Form1 : Form
    {
        string path;
        int start = 0;
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)//打开按钮
        {
            path = Application.StartupPath + "\\" + textBox1.Text;//完整路径名
            richTextBox1.LoadFile(path, RichTextBoxStreamType.RichText);//读取
        }
        private void button2_Click(object sender, EventArgs e)//保存按钮
        {
            richTextBox1.SaveFile(path, RichTextBoxStreamType.RichText);
        }
        private void button3_Click(object sender, EventArgs e)//查找按钮
        {
            start = richTextBox1.Find(textBox2.Text.Trim());
            richTextBox1.Focus();
        }
        private void button4_Click(object sender, EventArgs e)//替换按钮
        {
            start = start + textBox2.Text.Length;
            richTextBox1.SelectedText = textBox3.Text;
            richTextBox1.Focus();
        }
        private void button5_Click(object sender, EventArgs e)//查找下一个按钮
        {
            string strfind;
            strfind = textBox2.Text;
            start = start + strfind.Length;
            start = richTextBox1.Find(strfind, start, RichTextBoxFinds.None);
            if (start < 0)
                MessageBox.Show("已经搜索到文件末尾!");            
            richTextBox1.Focus();
        }
        private void button6_Click(object sender, EventArgs e)//替换全部按钮
        {
            richTextBox1.Text = richTextBox1.Text.Replace(textBox2.Text, textBox3.Text);
        }
    }
}

三.注意事项

关于RTF文件的路径,如下图所示:

四.运行截图 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值