您的位置:首页 > 编程语言 > C#

C#实现单词本功能

2020-04-02 12:08 1251 查看

本文实例为大家分享了C#实现单词本功能的具体代码,供大家参考,具体内容如下

看到网上有类似的教程视频实现单词本,于是自己敲了一个实现单词本功能的小项目,在实现期间,发现可以有两种版本来实现单词本功能,此处选择A版来为大家分享经验,同时留作自己日后复习巩固,有疏漏错误的地方,还望大神热心指出,在下感激不尽.

A版实现以下功能:

1.利用文件流读取文本文件
2.利用openfiledialog实现查找文件的功能
3.存取文本文件路径和显示文本文件内容的功能

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

namespace WindowsFormsApp6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button2_Click(object sender, EventArgs e)
{
textBox1.Clear();//每点击一次选择文件按钮自动清空文本框内已经打开的文件内容
textBox2.Clear();//清空文件路径的内容
OpenFileDialog filename = new OpenFileDialog();//定义打开文件
filename.InitialDirectory = Application.StartupPath;//初始路径
filename.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";//设置打开文件的类型
filename.FilterIndex = 2;//设置文件类型的显示顺序

if (filename.ShowDialog() == DialogResult.OK)
{
textBox2.Text = filename.FileName.ToString();//将路径显示在文本框
StreamReader sr = new StreamReader(filename.FileName, Encoding.Default);
//将文件通过stream流读取
string content = sr.ReadToEnd();//把文件读完存给content
string[] lines = content.Split('\n');//将文件内容分割成一行一行存给数组
for (int i = 0; i < lines.Length; i++)
{

textBox1.Text += lines[i++]+"\n";

//List<string> english = new List<string>();
//List<string> chinese = new List<string>();
//string[] words = lines[i].Trim().Split('\t');
//if (words.Length < 2)
//continue;
//english.Add(words[0]);
//chinese.Add(words[1]);

}
sr.Close();
}
}

private void button1_Click(object sender, EventArgs e)
{
textBox1.Clear();//此处点击返回按钮同样自动清空文本框文件内容
textBox2.Clear();//清除文件路径内容
}
}
}

以上为我编写的文件的代码,被注释掉的代码部分用以实现分割音标出来再显示的功能,还未完善好,所以注释掉了,有感兴趣的可以完善完善共同探讨。

这是我的窗口

我的文本文件内容是这样

这是实现的效果

项目任存在可改进的空间,有兴趣的伙伴可以改进改进,将你的作品放在评论区共同讨论

以上就是本文的全部内容,希望对大家的学习有所帮助

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C# 单词本