在c#中,如何在列表视图中显示特定的搜索段落号和docx文件名,而不重复相同的文件名
本文关键字:文件名 docx 段落号 视图 列表 显示 搜索 | 更新日期: 2023-09-27 17:54:52
我正在创建一个应用程序,其中用户在docx文件中搜索单词,并获得包含该单词的段落编号。几乎我的应用程序工作很好,但我所面临的问题是,我得到重复的文件名,并在新的列表视图行获得每个段落。让我们看一下图片,以便更好地理解。的形象。我只是想搜索的文件名和所有段落在一行列表视图分开与','逗号。让我们看看欲望图像。参见下面我尝试的代码
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++;
}
}
}
我认为您需要将yield返回移出内部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返回现在的位置,它从函数中返回,并在匹配的每行之后显示。将yield返回移出内循环应该使它只在每个文件完全搜索之后才返回。