我正在创建一个应用程序,其中用户搜索docx文件中的单词并获取包含该单词的段落编号。几乎我的应用程序工作正常,但我遇到的问题是我得到重复文件名并获取新listview行中的每个段落。让我们看看图像以获得更多的理解。 Image. 我只想通过与','逗号分开搜索文件名和listview的一行中的所有段落。让我们看看愿望image。 请参阅下面的代码我尝试
private void button2_Click(object sender, EventArgs e)
{
this.listView1.Items.Clear();
try
{
foreach (var filePath in Search(this.textBox1.Text, this.textBox2.Text, this.checkBox1.Checked, this.checkBox2.Checked, this.radioButton2.Checked))
{
var file = new FileInfo(filePath);
this.listView1.Items.Add(new ListViewItem(new string[] { file.Name, string.Format("{0:0.0}", file.Length / 1024d), file.FullName, toDisplay }));
}
}
catch (Exception ex)
{
MessageBox.Show(this, string.Format("Exception details:\n{0}", ex), string.Format("Exception '{0}' occurred.", ex.GetType()), MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private static IEnumerable<string> Search(string directory, string searchString, bool searchSubdirectories, bool caseSensitive, bool useRegex)
{
/*
* Below is the list where we insert all paragraph of docx file.
*/
var paragph = new List<string>();
/*
* Below I am using foreach loop by using this I get all docx files from a selected directory.
*/
foreach (var filePath in Directory.GetFiles(directory, "*.docx", searchSubdirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly))
{
string docxText;
int counter = 0;
using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
docxText = new DocxToStringConverter(stream).Convert();
string[] lines = docxText.Split(new string[] { Environment.NewLine },StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
if (line.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0)
{
//MessageBox.Show((counter + 1).ToString() + ": " + line);
paragph.Add((counter + 1).ToString());
arrparagh = paragph.ToArray();
toDisplay = string.Join(",", arrparagh);
//MessageBox.Show(toDisplay);
yield return filePath;
}
counter++;
}
}
}
答案 0 :(得分:0)
我相信你需要将收益率从内部foreach循环移出。像:
paragph.Clear();
foreach (string line in lines)
{
if (line.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0)
{
//MessageBox.Show((counter + 1).ToString() + ": " + line);
paragph.Add((counter + 1).ToString());
arrparagh = paragph.ToArray();
toDisplay = string.Join(",", arrparagh);
//MessageBox.Show(toDisplay);
}
counter++;
}
yield return filePath;
当你的收益率返回到现在的位置时,它将退出该函数并在匹配的每一行之后显示。将yield return从该内部循环移出应该使它仅在完全搜索每个文件后返回。