Как добавить progressBar на выполнение задачи?

Рейтинг: 0Ответов: 1Опубликовано: 06.03.2023

Написал программу, которая выводит название всех файлов выбранной папки в txt документ. Хочу "прикрутить" progressBar на выполнение. Никак не получается это сделать... Помогите пожалуйста. Дымлюсь уже(. Заранее спасибо.

Вот код программы:

private void Open_button_Click(object sender, EventArgs e)
{
     //выбор папки
    FolderBrowserDialog fb = new FolderBrowserDialog();
    if (fb.ShowDialog() == DialogResult.OK)
        item_textBox.Text = fb.SelectedPath;
}

private void OpenListFileName(string itemList)
{
    //получение названия файлов и вывод их в txt
    timer1.Start();
    DirectoryInfo dir = new DirectoryInfo(itemList);
    FileInfo[] fi = dir.GetFiles();

    SaveFileDialog saveFile = new SaveFileDialog
    {
        FileName = "Название",
        DefaultExt = "*.txt",
        Filter = "Текстовый файл|*.txt"
    };

    if (saveFile.ShowDialog() == DialogResult.OK && saveFile.FileName.Length > 0)
    {
        using (StreamWriter sw = new StreamWriter(saveFile.FileName, true))
        {
            for (int i = 0; i < fi.Length; ++i)
            {
                sw.WriteLine(fi[i].ToString());
            }
        }
    }
}

private void Run_button_Click(object sender, EventArgs e)
{
    OpenListFileName(item_textBox.Text);
}

private void Timer1_Tick(object sender, EventArgs e)
{
    if (progressBar1.Value > 100)
        timer1.Enabled = false;
    //else
    //    progressBar1.Value += 1;
}

Ответы

▲ 1Принят

Если почитать документацию, то там всё проще, чем вы делаете, не нужно вешать обработку прогресс бара на таймер, вы сами должны его дёргать примерно так, если скрестить пример из документации с вашим кодом:

    // Display the ProgressBar control.
    pBar1.Visible = true;
    // Set Minimum to 1 to represent the first file being copied.
    pBar1.Minimum = 1;
    // Set Maximum to the total number of files to process.
    pBar1.Maximum = fl.Length;
    // Set the initial value of the ProgressBar.
    pBar1.Value = 1;
    // Set the Step property to a value of 1 to represent each file being copied.
    pBar1.Step = 1;

    for (int i = 0; i < fi.Length; ++i)
    {
        sw.WriteLine(fi[i].ToString());
        pBar1.PerformStep();
    }

Больше ничего программировать не нужно. Только положить progressBar на форму и назвать его pBar1, как в примере из документации. ну или наоборот в коде всё переделать под ваше название этого контрола.