my program below is a simple windows form that searches for a file in the directory then it opens,reads and writes on it after that there is a search button which searches for words in the file but i can only do this with files that have a .txt extension can some help me i want to do this to word documents as well,i want to open files with .txt and .doc extensions if the file is another extension i want to pop up an error that it can not open the file this is my code below, is there anyone who can help me modify this program or give me ideas
namespace my_project
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog of = new OpenFileDialog();
of.ShowDialog();
textBox1.Text = of.FileName;
}
private void button2_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(textBox1.Text);
richTextBox1.Text = sr.ReadToEnd();
sr.Close();
}
private void button3_Click(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter(textBox1.Text, true);
sw.WriteLine(textBox2.Text);
sw.Close();
}
private void button4_Click(object sender, EventArgs e)
{
int index = 0; string temp = richTextBox1.Text; richTextBox1.Text = ""; richTextBox1.Text = temp;
while (index < richTextBox1.Text.LastIndexOf(textBox3.Text))
{
richTextBox1.Find(textBox3.Text, index, richTextBox1.TextLength, RichTextBoxFinds.None);
richTextBox1.SelectionBackColor = Color.Yellow;
index = richTextBox1.Text.IndexOf(textBox3.Text, index) + index;
}
}
}
}
Searching in .doc file will be a little hard, since doc files contain markup in order to give you the ability to decorate your text (with different font, bold, italic, margins, etc.). There are third party library and products that might help you with this one. Txt files on the other hand are plain text, that’s why you don’t have problems with this one.
In order to implement the validation, you can use the File static class and check the extension of the file and decide what to do next. You can also use the System.IO.Path.GetExtension method which takes the file name and gives you the extension.