I have a program I have to finish which involves opening a file that has numbers, displaying it, then also displaying how many numbers the file has and the sum of them.
Im currently stuck on how to add all the numbers read and display it :/
Here is my code:
private void btnReadRandomNumbers_Click(object sender, EventArgs e)
{
StreamReader inputFile;
try
{
int number = 0;
int count = 0;
int sum = 0;
lstRandomNumbers.Items.Clear();
if (fodOpenFile.ShowDialog() == DialogResult.OK)
{
inputFile = File.OpenText(fodOpenFile.FileName);
lstRandomNumbers.Items.Clear();
while (!inputFile.EndOfStream)
{
number = int.Parse(inputFile.ReadLine());
count = count + 1;
lstRandomNumbers.Items.Add(number);
}
lblNumberCount.Text = count.ToString();
lblSumNumbers.Text = number.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show("There is a problem with the disk file." + Environment.NewLine + ex.Message, "User Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
As seen in the Picture, the sum is only reading the last number of the list and im not sure why
Thanks for reading!
in line number = int.Parse(inputFile.ReadLine()); replaced number for each line!
you can write all code with this:
private void btnReadRandomNumbers_Click(object sender, EventArgs e)
{
try
{
lstRandomNumbers.Items.Clear();
if (fodOpenFile.ShowDialog() == DialogResult.OK)
{
var linesOfFile = File.ReadAllLines(fodOpenFile.FileName).Select(int.Parse).ToList();
lblSumNumbers.Text = linesOfFile.Sum().ToString();
lblNumberCount.Text = linesOfFile.Count().ToString();
lstRandomNumbers.DataSource = linesOfFile;
}
}
catch (Exception ex)
{
MessageBox.Show("There is a problem with the disk file." + Environment.NewLine + ex.Message, "User Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
You are almost there. Try your same code with minor modification. I have added inline comments.
private void btnReadRandomNumbers_Click(object sender, EventArgs e)
{
StreamReader inputFile;
try
{
int number = 0;
int count = 0;
int sum = 0;
//lstRandomNumbers.Items.Clear(); //don't need this
if (fodOpenFile.ShowDialog() == DialogResult.OK)
{
inputFile = File.OpenText(fodOpenFile.FileName);
//lstRandomNumbers.Items.Clear();//don't need this
while (!inputFile.EndOfStream)
{
number = int.Parse(inputFile.ReadLine());
count = count + 1;
//lstRandomNumbers.Items.Add(number);//don't need this
sum+=number; // add this
}
lblNumberCount.Text = count.ToString();
lblSumNumbers.Text = sum.ToString(); //change `number' to `sum`
}
}
catch (Exception ex)
{
MessageBox.Show("There is a problem with the disk file." + Environment.NewLine + ex.Message, "User Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
#Issa, Please let me know if this helps.
Give this a go:
private void btnReadRandomNumbers_Click(object sender, EventArgs e)
{
if (fodOpenFile.ShowDialog() == DialogResult.OK)
{
var lines = File.ReadAllLines(fodOpenFile.FileName);
var result =
lines
.Select(x => int.Parse(x))
.Aggregate(
new { count = 0, sum = 0 },
(a, x) => new { count = a.count + 1, sum = a.sum + x });
lstRandomNumbers.Items.Clear();
lstRandomNumbers.Items.AddRange(lines);
lblNumberCount.Text = result.count.ToString();
lblSumNumbers.Text = result.sum.ToString();
}
}
static void Main(string[] args)
{
var res = 0;
var r = new Regex(#"\d");// you can try "\d+" and you will see the difference
var matches = r.Matches("feawfwe312faewfa4gaeg1feaga67awfaw2");
if (matches != null && matches.Count > 0)
{
foreach (var m in matches)
res += int.Parse(m.ToString());
}
Console.WriteLine(res);
Console.ReadKey();
}
Related
I am creating and saving a csv file using saveFileDialog. I need to find a way to remember the pathName that the person saves the file to so that I can use the pathName to the file later on in the code.
The below code is what I have been trying, just to return the pathName but it will actually only be returning the sfd.FileName. Is there a way to get the full path?
private void saveCSVbutton_Click(object sender, EventArgs e)
{
saveShipping();
saveATT();
saveVerizon();
String shippingPath = saveShipping();
MessageBox.Show(shippingPath);
}
private String saveShipping()
{
if (dataGridView1.Rows.Count > 0)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "CSV (*.csv)|*.csv";
sfd.FileName = "shippingOutput.csv";
bool fileError = false;
if (sfd.ShowDialog() == DialogResult.OK)
{
if (File.Exists(sfd.FileName))
{
try
{//overwrite file
File.Delete(sfd.FileName);
}
catch (IOException ex)
{
fileError = true;
MessageBox.Show("It wasn't possible to write the data to the disk." + ex.Message);
}
}
if (!fileError)
{
try
{
int columnCount = dataGridView1.Columns.Count;
string columnNames = "";
string[] outputCsv = new string[dataGridView1.Rows.Count + 1];
for (int i = 0; i < columnCount; i++)
{
columnNames += dataGridView1.Columns[i].HeaderText.ToString() + ",";
}
outputCsv[0] += columnNames;
for (int i = 1; i < dataGridView1.Rows.Count; i++)
{
for (int j = 0; j < columnCount; j++)
{
outputCsv[i] += dataGridView1.Rows[i - 1].Cells[j].Value.ToString() + ",";
}
}
File.WriteAllLines(sfd.FileName, outputCsv, Encoding.UTF8);
MessageBox.Show("Data Exported Successfully", "Info");
String attachPathName = sfd.FileName;
}
catch (Exception ex)
{
MessageBox.Show("Error :" + ex.Message);
}
}
}
}
else
{
MessageBox.Show("No Record To Export", "Info");
}
return attachPathName;
}
There are 2 ways that I can think of that would keep it simple for you but they both kindoff work the same way, It depends on your requirements. I will just call it Method 1 and 2.
Method 1.
Preslave Tsenov has a good answer to keep it straight forward, However I noticed your SaveFileDialogue sfd variable is being Declared and Instantiated from within the method. So in short you will not be able to access it from outside the method block.
If you move the variable to just above the Constructor and declare it as Public(You want access to the variable from inside and outside the class) or as Private(You only want access to the variable from within your class). Once you have done that you should be able to call the variable at any moment.
Your code would then look something like this
public SaveFileDialog sfd = new SaveFileDialog();
private void saveCSVbutton_Click(object sender, EventArgs e)
{
saveShipping();
saveATT();
saveVerizon();
String shippingPath = saveShipping();
MessageBox.Show(shippingPath);
}
private String saveShipping()
{
if (dataGridView1.Rows.Count > 0)
{
sfd.Filter = "CSV (*.csv)|*.csv";
sfd.FileName = "shippingOutput.csv";
bool fileError = false;
if (sfd.ShowDialog() == DialogResult.OK)
{
if (File.Exists(sfd.FileName))
{
try
{//overwrite file
File.Delete(sfd.FileName);
}
catch (IOException ex)
{
fileError = true;
MessageBox.Show("It wasn't possible to write the data to the disk." + ex.Message);
}
}
if (!fileError)
{
try
{
int columnCount = dataGridView1.Columns.Count;
string columnNames = "";
string[] outputCsv = new string[dataGridView1.Rows.Count + 1];
for (int i = 0; i < columnCount; i++)
{
columnNames += dataGridView1.Columns[i].HeaderText.ToString() + ",";
}
outputCsv[0] += columnNames;
for (int i = 1; i < dataGridView1.Rows.Count; i++)
{
for (int j = 0; j < columnCount; j++)
{
outputCsv[i] += dataGridView1.Rows[i - 1].Cells[j].Value.ToString() + ",";
}
}
File.WriteAllLines(sfd.FileName, outputCsv, Encoding.UTF8);
MessageBox.Show("Data Exported Successfully", "Info");
String attachPathName = sfd.FileName;
}
catch (Exception ex)
{
MessageBox.Show("Error :" + ex.Message);
}
}
}
}
else
{
MessageBox.Show("No Record To Export", "Info");
}
return attachPathName;
}
Method 2
You could create a new class called "SessionVariables.cs" and a "SaveFileDialog sfd = new SaveFileDialog();" variable and declare it as public. You can then get and set the value at any anytime.
I have seen a few developers use this method, Specifically VB developers but it still works in C#. Just remember not to instantiate a new SaveFileDialog every time you use it or else the values will get cleared every time.
I hope this works for you or at least got you closer to a solution.
You can use Path.GetDirectoryName(sfd.FileName) to get full path to the file
I am running multiple instances of an application that reads first line from a file, then it deletes the first line and saves the file under the same name. I found out that in some instances the applications will crash. I created a sample program just to better understand the issues I have.
If I run four instances of this program, sometimes multiple instances attempt to delete the same line. In the end the operation succeeds, but it is not efficient. How can I improve the code to avoid this? Perhaps each instance needs to lock the file while it uses it.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Diagnostics;
namespace ConcurrentFileAccess
{
public partial class MainForm : Form
{
bool gbAbort = false;
public MainForm()
{
InitializeComponent();
}
void BtnCreateFileClick(object sender, EventArgs e)
{
string sFile = #"S:\Temp\concurrentFileAccess.txt";
Stopwatch stopwatch = Stopwatch.StartNew();
if (File.Exists(sFile)) {
File.Delete(sFile);
}
if (!File.Exists(sFile)) {
List<string> list = new List<string>();
var fc = File.Create(sFile);
fc.Close();
for (int i = 1; i <= 200; i++) {
list.Add(i.ToString());
}
File.WriteAllLines(sFile, list);
listBox1.Items.Add("File " + sFile + " was created and it contains 200 lines");
} else {
string[] lines = File.ReadAllLines(sFile);
int nlines = lines.Length;
listBox1.Items.Add("File " + sFile + " already exists and it contains " + nlines + " lines");
}
stopwatch.Stop();
listBox1.Items.Add("File created in " + stopwatch.Elapsed.ToString("hh\\:mm\\:ss\\.fff"));
}
void BtnDeleteFromFileClick(object sender, EventArgs e)
{
gbAbort = false;
int nlines = 9999;
while (nlines > 0) {
nlines = DeleteOneLine();
Application.DoEvents();
if (gbAbort) {
return;
}
}
}
int DeleteOneLine()
{
string sFile = #"S:\Temp\concurrentFileAccess.txt";
listBox1.Items.Add("We are in DeleteLines()...");
listBox1.SelectedIndex = listBox1.Items.Count - 1;
Application.DoEvents();
int nLinesLeft = 9999;
string line0 = string.Empty;
Stopwatch stopwatch = Stopwatch.StartNew();
int ntry = 0;
while (ntry < 100) {
try {
string[] lines = File.ReadAllLines(sFile);
List<string> list = new List<string>(lines);
nLinesLeft = list.Count;
if (nLinesLeft > 0) {
line0 = list[0];
list.RemoveAt(0);
listBox1.Items.Add("Deleted line " + line0);
listBox1.SelectedIndex = listBox1.Items.Count - 1;
Application.DoEvents();
listBox1.Items.Add("Writing to file after line " + line0 + " was deleted");
File.WriteAllLines(sFile, list);
nLinesLeft = list.Count;
Application.DoEvents();
} else {
nLinesLeft = 0;
break;
}
} catch (Exception) {
ntry++;
listBox1.Items.Add("ntry = " + ntry + ", could not delete line " + line0 + " from file. Attempting again...");
listBox1.SelectedIndex = listBox1.Items.Count - 1;
Application.DoEvents();
Application.DoEvents();
Thread.Sleep(50);
}
}
if(ntry >= 100) {
nLinesLeft = -1; // should never get here
}
stopwatch.Stop();
listBox1.Items.Add("ntry: " + ntry + ", lines Left: " + nLinesLeft + ", elapsed = " + stopwatch.Elapsed.ToString("hh\\:mm\\:ss\\.fff"));
listBox1.SelectedIndex = listBox1.Items.Count - 1;
Application.DoEvents();
return nLinesLeft;
}
void BtnAbortClick(object sender, EventArgs e)
{
gbAbort = true;
}
void BtnOpenAppFolderClick(object sender, EventArgs e)
{
string sFile = Application.ExecutablePath;
string sPath = Path.GetDirectoryName(sFile);
Process.Start(sPath);
}
void BtnOpenFileClick(object sender, EventArgs e)
{
string sFile = #"S:\Temp\concurrentFileAccess.txt";
if(File.Exists(sFile)) {
Process.Start(sFile);
}
else {
MessageBox.Show("File " + sFile + " not found");
}
}
}
}
I have a simple wpf c# app that takes the text from the inputField tries to find some info there and returns the result into outputField.
Here is the code:
private void FindButton_Click(object sender, RoutedEventArgs e)
{
try
{
string parsed = string.Empty;
if (string.IsNullOrWhiteSpace(new TextRange(InputField.Document.ContentStart, InputField.Document.ContentEnd).Text));
{
OutputField.Document.Blocks.Clear();
MessageBox.Show("Empty input");
}
else
{
Parser nOb = new Parser(new TextRange(InputField.Document.ContentStart, InputField.Document.ContentEnd).Text);
string[] result = nOb.findAddresses();
if (result.Length == 0)
{
OutputField.Document.Blocks.Clear();
MessageBox.Show("Nothing found");
}
else
{
for (int i = 0; i < result.Length; i++)
{
parsed += result[i] + Environment.NewLine;
}
OutputField.Document.Blocks.Clear();
OutputField.Document.Blocks.Add(new Paragraph(new Run(parsed)));
MessageBox.Show("Success");
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
What I want to do is to change FindButton text from "Find" to "Searching..." and back when the search is completed.
I tried to add the following code just before try{}:
FindButton.Content = "Searching...";
FindButton.IsEnabled = false;
And changed it back after try{} to "Find" but it didn't work.
As I read somewhere I need to use async method here or threading.
I found a few solutions here and tried to add "async" to my function and also changed the code:
await Task.Run(() => {
//My code which is above
});
But it started returning the following error:
MS.Internal.PtsHost.UnsafeNativeMethods.PTS.SecondaryException
NullReferenceException
I'm completely new to these topics and don't know how to make it work. Please someone help.
Assuming that your findAddresses() method access UI elements and must be executed on the UI thread you could try to use Task.Delay to give the UI thread a chance to update the FindButton just before you kick of your operation. Try this:
private async void FindButton_Click(object sender, RoutedEventArgs e)
{
FindButton.Content = "Searching...";
FindButton.IsEnabled = false;
await Task.Delay(1);
try
{
string parsed = string.Empty;
if (string.IsNullOrWhiteSpace(new TextRange(InputField.Document.ContentStart, InputField.Document.ContentEnd).Text)) ;
{
OutputField.Document.Blocks.Clear();
MessageBox.Show("Empty input");
}
else
{
Parser nOb = new Parser(new TextRange(InputField.Document.ContentStart, InputField.Document.ContentEnd).Text);
string[] result = nOb.findAddresses();
if (result.Length == 0)
{
OutputField.Document.Blocks.Clear();
MessageBox.Show("Nothing found");
}
else
{
for (int i = 0; i < result.Length; i++)
{
parsed += result[i] + Environment.NewLine;
}
OutputField.Document.Blocks.Clear();
OutputField.Document.Blocks.Add(new Paragraph(new Run(parsed)));
MessageBox.Show("Success");
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
FindButton.Content = "Default";
FindButton.IsEnabled = true;
}
This program is about inserting expenses someone is making so in the textboxes i have to insert only numbers. So I have to save all those numbers from the textboxes into a txt file, but summed. Can you help me with some ideas?
private void button2_Click_1(object sender, EventArgs e)
{
try
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(textBox1.Text + " " + textBox2.Text + " " + textBox3.Text + " " + textBox4.Text);
File.WriteAllText(fileName, sb.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Here's a robust approach to read out numbers from TextBoxes and write them to an output file:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
try
{
// populate textboxes
var boxs = new[] {textBox1, textBox2};
// get user input
var decimals = new List<decimal>();
var expenses = GetExpenses(boxs, decimals);
if (!expenses)
throw new InvalidOperationException("Expecting numbers");
// write to file
using (var stream = File.Create("output.txt"))
using (var writer = new StreamWriter(stream))
{
foreach (var d in decimals)
{
writer.WriteLine(d);
}
var total = decimals.Sum();
writer.WriteLine("Total: " + total);
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
private bool GetExpenses(TextBox[] boxs, List<decimal> list)
{
if (boxs == null) throw new ArgumentNullException(nameof(boxs));
if (list == null) throw new ArgumentNullException(nameof(list));
foreach (var box in boxs)
{
var text = box.Text;
decimal result;
if (!decimal.TryParse(text, out result))
return false;
list.Add(result);
}
return true;
}
}
}
You would need a line that adds up the numbers like this:
private void button2_Click_1(object sender, EventArgs e)
{
try
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(textBox1.Text + " " + textBox2.Text+ " " + textBox3.Text+ " " + textBox4.Text);
sb.AppendLine((Int32.Parse(textBox1.Text) + Int32.Parse(textBox2.Text) + Int32.Parse(textBox3.Text) + Int32.Parse(textBox3.Text)).ToString())
File.WriteAllText(fileName, sb.ToString());
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Backgroundworker dowork event
string CurrentFileWithPath;
private void _FileProcessingWorker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
DirectoryInfo[] MySubDirectories = (DirectoryInfo[])e.Argument;
for (int i = 0; i < MySubDirectories.GetLength(0); i++)
{
DirectoryInfo MySubDirectory = MySubDirectories[i];
List<FileInfo> l = new List<FileInfo>();
CountFiles(MySubDirectory, l);
int totalFiles = l.Count;
object[] CurrentStatus = new object[5];
CurrentStatus[3] = i.ToString();
CurrentStatus[4] = totalFiles.ToString();
_FileProcessingWorker.ReportProgress(0, CurrentStatus);
string CurrentDirectory = "Current Directory: " + MySubDirectory.Name;
foreach (FileInfo MyFile in l)
{
CurrentStatus = new object[5];
if (_FileProcessingWorker.CancellationPending)
{
e.Cancel = true;
return;
}
if (MyFile.Extension.ToLower() == ".cs" || MyFile.Extension.ToLower() == ".vb")
{
string CurrentFile = "Current File: " + MyFile.Name;
string CurrentFileWithPath = MyFile.FullName;
CurrentStatus[0] = CurrentDirectory;
CurrentStatus[1] = CurrentFile;
_FileProcessingWorker.ReportProgress(0, CurrentStatus);
List<string> Result = SearchInFile(CurrentFileWithPath, "static class FileShellExtension");
if (Result != null && Result.Count > 0)
{
CurrentStatus[2] = Result;
_FileProcessingWorker.ReportProgress(0, CurrentStatus);
}
}
}
}
}
catch (Exception err)
{
return;
}
Progresschanged event
private void _FileProcessingWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (typeof(object[]) == e.UserState.GetType())
{
object[] StatusMsg = (object[])e.UserState;
if (5 == StatusMsg.GetLength(0))
{
label2.Text = StatusMsg[4].ToString();
label4.Text = StatusMsg[3].ToString();
if (StatusMsg[0] != null && StatusMsg[1] != null)
{
lblCurrentDirectory.Text = StatusMsg[0].ToString();
lblStatus.Text = StatusMsg[1].ToString();
}
if (StatusMsg[2] != null)
{
if (StatusMsg[2].GetType() == typeof(List<string>))
{
List<string> l = (List<string>)StatusMsg[2];
for (int i = 0; i < l.Count; i++)
{
ListViewCostumControl.lvnf.Items.Add("Directory: " + lblCurrentDirectory.Text + "In File: " + lblStatus.Text + l[i]);
w.WriteLine("Directory: " + lblCurrentDirectory.Text + "In File: " + lblStatus.Text + l[i]);
}
}
}
}
}
}
CountFiles method
private void CountFiles(DirectoryInfo di, List<FileInfo> l)
{
try
{
l.AddRange(di.EnumerateFiles());
}
catch
{
string fff = "";
}
try
{
IEnumerable<DirectoryInfo> subDirs = di.EnumerateDirectories();
if (subDirs.Count() > 0)
{
foreach (DirectoryInfo dir in subDirs)
CountFiles(dir, l);
}
}
catch
{
string yyy = "";
}
}
SearchInFile method
private List<string> SearchInFile(string fileToSearch, string textToSearch)
{
List<string> l = new List<string>();
try
{
foreach (var line in File.ReadAllLines(fileToSearch))
{
if (line.Contains(textToSearch))
l.Add(line);
}
}
catch(Exception err)
{
string fff = err.ToString();
}
return l;
}
The first problem is when getting the number of directories:
private void btnProcess_Click(object sender, EventArgs e)
{
btnProcess.Enabled = false;
btnDirectory.Enabled = false;
btnCancel.Visible = true;
btnCancel.Enabled = true;
btnCancel.Text = "Cancel";
MyProgressBar.Visible = true;
_FileProcessingWorker = new BackgroundWorker();
_FileProcessingWorker.WorkerReportsProgress = true;
_FileProcessingWorker.WorkerSupportsCancellation = true;
_FileProcessingWorker.DoWork += new DoWorkEventHandler(_FileProcessingWorker_DoWork);
_FileProcessingWorker.ProgressChanged += new ProgressChangedEventHandler(_FileProcessingWorker_ProgressChanged);
_FileProcessingWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_FileProcessingWorker_RunWorkerCompleted);
string BasePath = lblDirectoryName.Text;
DirectoryInfo MyDirectory = new DirectoryInfo(BasePath);
DirectoryInfo[] MySubDirectories = MyDirectory.GetDirectories();
int SubDirectoryCount = MySubDirectories.GetLength(0);
MyProgressBar.Minimum = 0;
MyProgressBar.Step = 1;
MyProgressBar.Maximum = SubDirectoryCount;
MyProgressBar.Value = MyProgressBar.Minimum;
_LastCounter = 0;
_FileProcessingWorker.RunWorkerAsync(MySubDirectories);
}
In the click button i'm getting the sub directories.
But there are two problems.
In the dowork event when i put a break point on this line:
for (int i = 0; i < MySubDirectories.GetLength(0); i++)
I see that it contain 409 directories. But when i report the number of directories to the label4 in the dowork event
CurrentStatus[3] = i.ToString();
In the progresschanged event
label4.Text = StatusMsg[3].ToString();
I see in the end on label4 408 directories. And in D:(in this case i'm working on my D:\ directory) when i select all the directories in windows explorer make right click and properties i see only 405 directories. So what is the real number of directories ? What and how number of directories should i display in label4 ?
The second problem is when i report the number of files in dowork event:
CurrentStatus[4] = totalFiles.ToString();
And in progresschanged event show it on label2:
label2.Text = StatusMsg[4].ToString();
The problem is that the totalFiles value is changing all the time once it's 2 then it's 768 then it's 66 then 8987 but what i want to do is somehow to sum in real time the values in totalFiles so in label2 i will see first time for example: 2 then 770 then (770+66) so i will see in label2 816....to see always the sum of all the values so far.
The last problem is in the progresschanged event this loop:
for (int i = 0; i < l.Count; i++)
{ ListViewCostumControl.lvnf.Items.Add("Directory: " + lblCurrentDirectory.Text + "In File: " + lblStatus.Text + l[i]);
w.WriteLine("Directory: " + lblCurrentDirectory.Text + "In File: " + lblStatus.Text + l[i]);
}
It might be logic somehow to take out and make this loop at this time in the program in another backgroundworker like backgroundworker2 dowork event ? If so how to do it ? The problem is when the loop have many items to add to the listView it make the program to hang until the loop finish.
Each time you execute
CurrentStatus[4] = totalFiles.ToString();
You are resetting the status value to the count of files in the current processing directory. This is why the number keeps bouncing around. Instead I would suggest:
int thisDirFiles;
thisDirFiles = l.Count;
totalFiles += thisDirFiles;
CurrentStatus[4] = totalFiles.ToString();
Now when you report progress, CurrentStatus[4] will have the running total.
For your second question, it looks to me you are trying to do too much when you are reporting progress. Manipulating ListViews can be costly, and you are probably spending more time updating the ListView than you are processing the directories, so your machine seems to freeze.