在文件中搜索文本时如何重复搜索而不重新检索文件?

时间:2017-08-23 20:45:38

标签: c# .net winforms

我在搜索时做了两种方法。首先检索文件,然后在文件中搜索。

但在某些情况下,我只更改我搜索的搜索文本,我想在相同的目录和文件中重复搜索。那么我怎么能让它记住最后检索到的文件呢?

这是启动backgorundworker的按钮点击事件和搜索方法:

private void startButton_Click(object sender, EventArgs e)
        {
            ListViewCostumControl.lvnf.Items.Clear();
            numberoffiles = 0;
            numberofrestrictedFiles = 0;
            numberofdirs = 0;
            label24.Text = "0";
            label1.Text = "0";
            label15.Text = "0";
            Logger.Write("Operation started");
            label21.Text = "Phase 1: Retrieving files";
            label21.Visible = true;
            startButton.Enabled = false;
            stopButton.Enabled = true;
            pauseresumeButton.Enabled = true;
            label1.Select();
            timer1.Start();
            if (!backgroundWorker1.IsBusy)
            {
                SetWorkerMode(true);
                backgroundWorker1.RunWorkerAsync();
            }
        }

这是已完成的背景工作事件,我们正在向文本文件写入一些信息,但不是整个检索到的文件。

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            _stopwatch.Restart();
            string[] values = textBox1.Text.Split(new string[] { ",," }, StringSplitOptions.None);
            DirSearch(textBox3.Text, textBox2.Text, values, worker, e);
            _stopwatch.Stop();
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            MyProgress mypro = (MyProgress)e.UserState;
            ListViewCostumControl.lvnf.Items.Add(mypro.Report1);
            label15.Text = mypro.Report2;
            label15.Visible = true;
            if (ListViewCostumControl.lvnf.Items.Count > 9)
                textBox4.Enabled = true;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled == true)
            {
                label1.Select();
                _stopwatch.Stop();
                label24.Text = "0";
                label5.Text = "00:00:00";
                label1.Text = "0";
                label11.Text = "0";
                label15.Text = "0";
                label24.Text = "0";
                pauseresumeButton.Enabled = false;
                stopButton.Enabled = false;
                startButton.Enabled = true;
                timer1.Stop();
                ListViewCostumControl.lvnf.Items.Clear();
                Logger.Write("Operation cancelled");
                button4.Enabled = true;
            }
            if (e.Error != null)
            {

            }
            else
            {
                label1.Select();
                _stopwatch.Stop();
                timer1.Stop();
                stopButton.Enabled = false;
                pauseresumeButton.Enabled = false;
                startButton.Enabled = true;
                label21.Text = "Last operation ended at: " + DateTime.Now;
                Logger.Write("Number of retrieved files: " + numberoffiles);
                Logger.Write("Number of restricted files: " + numberofrestrictedFiles);
                Logger.Write("Number of searched files: " + numberofdirs);
                Logger.Write("Number of results: " + label15.Text);
                Logger.Write("Searched root directory: " + textBox3.Text);
                Logger.Write("Operation time: " + _stopwatch.Elapsed);
                Logger.Write("Operation ended");
                Logger.Write(" ");
                button4.Enabled = true;
                mCompleted = true;
                if (mClosePending) this.Close();
            }
        }

这是搜索方法:

int numberofdirs = 0;
        void DirSearch(string rootDirectory, string filesExtension, string[] textToSearch, BackgroundWorker worker, DoWorkEventArgs e)
        {
            List<string> resultsoftextfound = new List<string>();
            List<string> resultsoftextfound1 = new List<string>();
            List<string> filePathList = new List<string>();
            int numberoffiles = 0;
            try
            {
                filePathList = SearchAccessibleFilesNoDistinct(rootDirectory, null,worker,e).ToList();
            }
            catch (Exception err)
            {
                string ad = err.ToString();
            }
            label21.Invoke((MethodInvoker)delegate
                    {
                        label21.Text = "Phase 2: Searching in files";
                    });
            MyProgress myp = new MyProgress();
            myp.Report4 = filePathList.Count.ToString();
            foreach (string file in filePathList)
            {
                try
                {
                    _busy.WaitOne();
                    if (worker.CancellationPending == true)
                    {
                        e.Cancel = true;
                        return;
                    }

                    bool reportedFile = false;

                    for (int i = 0; i < textToSearch.Length; i++)
                    {
                        if (File.ReadAllText(file).IndexOf(textToSearch[i], StringComparison.InvariantCultureIgnoreCase) >= 0)
                        {
                            resultsoftextfound.Add(file + "  " + textToSearch[i]);
                            if (!reportedFile)
                            {
                                numberoffiles++;

                                myp.Report1 = file;
                                myp.Report2 = numberoffiles.ToString();
                                myp.Report3 = textToSearch[i];
                                backgroundWorker1.ReportProgress(0, myp);
                                reportedFile = true;
                            }
                        }
                    }
                    numberofdirs++;
                    label1.Invoke((MethodInvoker)delegate
                    {
                        label1.Text = string.Format("{0}/{1}", numberofdirs, myp.Report4);
                        label1.Visible = true;
                    });
                }
                catch (Exception)
                {

                }
            }
        }

和SearchAccessibleFilesNoDistinct方法:

string restrictedFile = "";
        List<string> restrictedFiles = new List<string>();
        int numberofrestrictedFiles = 0;
        int numberoffiles = 0;
        IEnumerable<string> SearchAccessibleFilesNoDistinct(string root, List<string> files,BackgroundWorker worker, DoWorkEventArgs e)
        {
            _busy.WaitOne();
            if (files == null)
                files = new List<string>();
            if (Directory.Exists(root))
            {
                foreach (var file in Directory.EnumerateFiles(root))
                {
                    if (worker.CancellationPending == true)
                    {
                        e.Cancel = true;
                        return files;
                    }
                    restrictedFile = file;
                    string ext = Path.GetExtension(file);
                    if (!files.Contains(file) && ext == textBox2.Text)
                    {
                        files.Add(file);
                    }
                    numberoffiles++;
                    label24.Invoke((MethodInvoker)delegate
                    {
                        label24.Text = numberoffiles.ToString();
                        label24.Visible = true;
                    });
                }
                foreach (var subDir in Directory.EnumerateDirectories(root))
                {
                    if (worker.CancellationPending == true)
                    {
                        e.Cancel = true;
                        return files;
                    }
                    try
                    {
                        SearchAccessibleFilesNoDistinct(subDir, files,worker, e);
                    }
                    catch (UnauthorizedAccessException)
                    {
                        restrictedFiles.Add(restrictedFile);
                        numberofrestrictedFiles++;
                        label11.Invoke((MethodInvoker)delegate
                        {
                            label11.Text = numberofrestrictedFiles.ToString();
                            label11.Visible = true;
                        });
                        continue;
                    }
                }
            }
            return files;
        }

这个想法是给用户和选项选择是否以某种方式保存最后检索到的文件,因此当他重复搜索时,它将不再检索整个文件,只会搜索它们。换句话说,如果我重复最后一次搜索,只需制作第二种方法。

我称之为第1阶段和第2阶段。

问题可能是,如果我将最后检索到的文件保存到文本文件或类似的东西,它可能是硬盘上的大文件?

另一个问题是,当我输入要在textBox1中搜索的文本时,如果我输入两个带空格的单词,例如没有空格则不一样:Form1与Form 1不同我怎么做它将搜索结果Form1和Form 1?

private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (textBox1.Text != "" && textBox3.Text != "" && Directory.Exists(textBox3.Text))
            {
                startButton.Enabled = true;
                Properties.Settings.Default["Setting2"] = textBox1.Text;
                Properties.Settings.Default.Save();
            }
            else
            {
                startButton.Enabled = false;
            }
        }

如果用户输入textBox1,

,我就这样做了

它会将其后的文本视为另一个搜索文本。

void lvnf_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ListViewCostumControl.lvnf.SelectedItems.Count > 0)
            {
                results = new List<int>();
                richTextBox1.Text = File.ReadAllText(ListViewCostumControl.lvnf.Items[ListViewCostumControl.lvnf.SelectedIndices[0]].Text);
                FileInfo fi = new FileInfo(ListViewCostumControl.lvnf.Items[ListViewCostumControl.lvnf.SelectedIndices[0]].Text);
                label17.Text = ExtensionMethods.ToFileSize(fi.Length);
                label17.Visible = true;
                filePath = Path.GetDirectoryName(fi.FullName);
                string word = textBox1.Text;
                string[] test = word.Split(new string[] { ",," }, StringSplitOptions.None);
                foreach (string myword in test)
                {
                    HighlightPhrase(richTextBox1, myword, Color.Yellow);
                    label16.Text = results.Count.ToString();
                    label16.Visible = true;
                    if (results.Count > 0)
                    {
                        numericUpDown1.Maximum = results.Count;
                        numericUpDown1.Enabled = true;
                        richTextBox1.SelectionStart = results[(int)numericUpDown1.Value - 1];
                        richTextBox1.ScrollToCaret();
                    }
                }
            }
        }

例如,如果我键入以搜索Form1,表单1

然后它将搜索Form1和Form 1的所有结果

或者如果我输入Form1,帮助

然后结果也将用于Form1和帮助。

问题不确定问题是否更具逻辑性。当我只键入Form1时,我应该以某种方式将其视为表单1,或者我应该保留它,因为它现在是Form1,Form 1?

在我搜索SwitchCameras之前,它找到了结果,但在此之前我搜索了Switch Cameras并且它没有找到任何结果,而且我没有在Switch Cameras之间放置。

所以我认为通过逻辑Switch Cameras也应该找到SwitchCameras。

那么如何更改此搜索规则,如果没有,但是单词之间还有一个空格搜索一个单词?

Switch Cameras也会找到SwitchCameras但Switch,Cameras可能会找到更多结果。

0 个答案:

没有答案