Reputation: 89
I'm currently trying to read a textfile and extract all email addresses in it. Got this working with the following function:
My C# function:
public void extractMails(string filePath)
{
List<string> mailAddressList = new List<string>();
string data = File.ReadAllText(filePath);
Regex emailRegex = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.IgnoreCase);
MatchCollection emailMatches = emailRegex.Matches(data);
StringBuilder sb = new StringBuilder();
foreach (Match emailMatch in emailMatches)
{
sb.AppendLine(emailMatch.Value);
}
string exePath = System.Reflection.Assembly.GetEntryAssembly().Location;
string dirPath = Path.GetDirectoryName(exePath);
File.WriteAllText(dirPath + "extractedEmails.txt", sb.ToString());
}
Now I have added a progressbar, since the loaded text-file can be huge. How could I fill the progressbar while the function is beeing executed that the progressbar would be filled to 100% in the end?
I would appreciate any kind of help.
Upvotes: 0
Views: 1806
Reputation: 48686
@user3185569 comment is correct. I am offering a different kind of solution without using async
or await
, just in case you are using an older version of Visual Studio.
Basically you need to spin your task up in a new thread, then use Invoke()
to update the progress bar. Here is a simple example:
private int _progress;
private delegate void Delegate();
private void btnStartTask_Click(object sender, EventArgs e)
{
// Initialize progress bar to 0 and task a new task
_progress = 0;
progressBar1.Value = 0;
Task.Factory.StartNew(DoTask);
}
private void DoTask()
{
// Simulate a long 5 second task
// Obviously you'll replace this with your own task
for (int i = 0; i < 5; i++)
{
System.Threading.Thread.Sleep(1000);
_progress = (i + 1)*20;
if (progressBar1.InvokeRequired)
{
var myDelegate = new Delegate(UpdateProgressBar);
progressBar1.Invoke(myDelegate);
}
else
{
UpdateProgressBar();
}
}
}
private void UpdateProgressBar()
{
progressBar1.Value = _progress;
}
Upvotes: 2
Reputation: 193
You just iterate through all the objects in the file that you want. You need the amount of objects in there,then you multiply the current iterator by 100 divided by the total amount of objects. Theres your persentage. Now update the process of the bar with the value you got.
Upvotes: 0