按掩码仅搜索列表框中的选定名称,然后将结果写入txt文件

时间:2019-01-28 19:02:14

标签: c# listbox

stackoverflowers)!

我尝试使用以下代码:

将匹配项写入一个文件...但是我的算法会重写数据并引发异常

    private void button8_Click(object sender, EventArgs e) // adding

    {
        if (listBox1.SelectedIndex != -1)
        {
            DirectoryInfo dinfo = new DirectoryInfo(@"C:\Users\lavraschuk\Desktop\Files\");
            string folderName = dinfo.FullName;
            string filepath = Path.Combine(folderName, listBox1.Items[listBox1.SelectedIndex].ToString());
            if (File.Exists(filepath))
                searchMask2(listBox1); // using MaskMethod with current file
                listBox1.Items.RemoveAt(listBox1.SelectedIndex);
        }

        MessageBox.Show("File txt is ready");
    }

    void searchMask2(ListBox listBox1) // Search Method
    {
        {
            for (int i = listBox1.Items.Count - 1; i >= 0; i--)
            {
                if (listBox1.GetSelected(i))
                {
                    //string rootFolder = @"C:\Users\Anton\Desktop\С#folder";
                    string pattern = @"\b(I am happy*)\b";
                    using (StreamWriter sw = File.CreateText(@"C:\Users\Desktop\Target\target.txt"))
                    //foreach (var file in Directory.EnumerateFiles(rootFolder, "*.txt", SearchOption.AllDirectories))
                    //{
                    using (StreamReader sr = new StreamReader(listBox1.Items[i].ToString(), System.Text.Encoding.Default))
                    //using (StreamReader sr = new StreamReader(listBox1.Items[i].ToString(), true, System.Text.Encoding.Default))
                    {
                        string line;
                        while ((line = sr.ReadLine()) != null)
                        {
                            string newstring = line.Substring(0, 8);
                            Match match = Regex.Match(line, pattern, RegexOptions.IgnoreCase);
                            var name = Path.GetFileName(listBox1.Items[i].ToString());

                            if (match.Success)
                            {
                                var jk = (name + " " + newstring + " " + match.Value);
                                sw.WriteLine(jk);
                            }
                            else
                                sw.Write("");
                        }
                    }
                }
            }
        }
    }

我希望我的代码执行以下方面:

1)在列表框中选择的文件中搜索

2)将匹配项写入名为target.txt的文件

3)使用列表框中的文件名时-该名称应从此处消失

0 个答案:

没有答案