简体   繁体   中英

How to show progress bar while reading multiple text files

I am reading text files line by line from subfolders one by one. That means once it completes the reading of all the text files containing one subfolder then start reading files from the next subfolder. That you can understand from my code. Everything is working fine , what I want is to show a progress bar when it starts the reading from the very first file and then hide the progress bar when the execution finished. Any help can be appreciated. Below is my code :

private void browse_Click(object sender, EventArgs e)
    {
        try
        {
            string newFileName1 = "";
            string newFileName2 = "";
            week = textBox2.Text;
            if (week == null || week == "")
            {
                MessageBox.Show("Week cannot be null.");
                return;
            }


            DialogResult result = folderBrowserDialog1.ShowDialog();

            if (result == DialogResult.OK)
            {
                DateTime starttime = DateTime.Now;

                string folderPath = Path.GetDirectoryName(folderBrowserDialog1.SelectedPath);
                string folderName = Path.GetFileName(folderPath);
                DirectoryInfo dInfo = new DirectoryInfo(folderPath);

                foreach (DirectoryInfo folder in dInfo.GetDirectories())
                {
                    newFileName1 = "Files_with_dates_mismatching_the_respective_week_" + folder.Name + ".txt";
                    newFileName2 = "Files_with_wrong_date_format_" + folder.Name + ".txt";

                    if (File.Exists(folderPath + "/" + newFileName1))
                    {
                        File.Delete(folderPath + "/" + newFileName1);
                    }

                    if (File.Exists(folderPath + "/" + newFileName2))
                    {
                        File.Delete(folderPath + "/" + newFileName2);
                    }

                    FileInfo[] folderFiles = folder.GetFiles();

                    if (folderFiles.Length != 0)
                    {
                        List<Task> tasks = new List<Task>();
                        foreach (var file in folderFiles)
                        {
                            var task = ReadFile(file.FullName, folderPath, folder.Name, week);
                            tasks.Add(task);
                        }

                        Task.WhenAll(tasks.ToArray());
                        DateTime stoptime = DateTime.Now;
                        TimeSpan totaltime = stoptime.Subtract(starttime);
                        label6.Text = Convert.ToString(totaltime);
                        textBox1.Text = folderPath;

                    }
                }
                DialogResult result2 = MessageBox.Show("Read the files successfully.", "Important message", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        catch (Exception)
        {

            throw;
        }
    }

    public async Task ReadFile(string file, string folderPath, string folderName, string week)
    {
        int LineCount = 0;
        string fileName = Path.GetFileNameWithoutExtension(file);

        using (FileStream fs = File.Open(file, FileMode.Open))
        using (BufferedStream bs = new BufferedStream(fs))
        using (StreamReader sr = new StreamReader(bs))
        {
            for (int i = 0; i < 2; i++)
            {
                sr.ReadLine();
            }

            string oline;
            while ((oline = sr.ReadLine()) != null)
            {
                LineCount = ++LineCount;
                string[] eachLine = oline.Split(';');

                string date = eachLine[30].Substring(1).Substring(0, 10);

                DateTime dt;

                bool valid = DateTime.TryParseExact(date, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);

                if (!valid)
                {
                    StreamWriter sw = new StreamWriter(folderPath + "/" + "Files_with_wrong_date_format_" + folderName + ".txt", true);
                    await sw.WriteLineAsync(fileName + "  " + "--" + "  " + "Line number :" + " " + LineCount);
                    sw.Close();
                }
                else
                {
                    DateTime Date = DateTime.ParseExact(date, "d/M/yyyy", CultureInfo.InvariantCulture);

                    int calculatedWeek = new GregorianCalendar(GregorianCalendarTypes.Localized).GetWeekOfYear(Date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Saturday);

                    if (calculatedWeek == Convert.ToInt32(week))
                    {

                    }
                    else
                    {
                        StreamWriter sw = new StreamWriter(folderPath + "/" + "Files_with_dates_mismatching_the_respective_week_" + folderName + ".txt", true);
                        await sw.WriteLineAsync(fileName + "  " + "--" + "  " + "Line number :" + " " + LineCount);
                        sw.Close();
                    }
                }
            }
        }
    }

Do you want to show progress for each file itself or for all files in one?

You can get your file size with:

FileInfo fileInfo = new FileInfo(file);
long fileLength = fileInfo.Length;

Set your progress bar minimum to 0 and maximum to 100. Create a variable containing the current stream position and then update your progress bar with:

(int)(((decimal)currentStreamPosition / (decimal)fileLength)*(decimal)100);

You can either add all file sizes and show percentage or set the currentStreamPosition to zero when finished reading one file.

You have to traverse all files you need to read before getting the exact file size in sum.

Generally, in similar situations, it is better to show 2 progress bars if possible - one for Overall progress, another for Current. So, you can count all files in all SubFolders first to estimate Overall progress and then show reading of each file in Current progress bar.

If progress bar should be only one - than only Overall progress can be displayed. You can count files number with Directory.GetFiles method. See following link https://msdn.microsoft.com/en-us/library/3hwtke0f.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM