简体   繁体   English

BackgroundWorker C#,从txt文件读取-写入csv

[英]BackgroundWorker C#, Read from txt files - Write to a csv

The following code actually does what i want it to do however I'm trying to make it optimal and as im still learning about the BackgroundWorker etc I thought you could give me a few tips. 下面的代码实际上完成了我想要的操作,但是我正在尝试使其达到最佳状态,并且由于我仍在学习BackgroundWorker等,因此我认为您可以给我一些提示。 The trouble is I can run the program but because it's quite a long operation (1000's+ lines per text file), it doeant update the progressbar or labels very well only until the program completes. 麻烦的是我可以运行该程序,但是由于操作时间很长(每个文本文件1000行以上),因此它只能在程序完成之前很好地更新进度条或标签。 there are 2 progreesbars, one for the number of text files processed and the other for the number of lines read of the text file in the process. 有2个progreesbar,一个用于处理的文本文件数,另一个用于在处理过程中读取文本文件的行数。

namespace myParser
{
    public partial class Form1 : Form
{

    string filePath;
    string[] files;

    public Form1()
    {
        InitializeComponent();

        pbFilesProcessed.Visible = false;
        pbLinesProcessed.Visible = false;
        btnParse.Visible = false;
        lbProcessedFiles.Visible = false;
        lbProcessedLines.Visible = false;
    }

    private void btnOpen_Click(object sender, EventArgs e)
    {
        DialogResult result = folderBrowserDialog1.ShowDialog();
        if (result == DialogResult.OK)
        {
            //counts the number of files in the folder
            files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);

            filePath = folderBrowserDialog1.SelectedPath.ToString();

            char[] delimiterChars = { '\\' };
            string[] filePathParts = filePath.Split(delimiterChars);

            string folder = filePathParts[4];

            tbFolderName.Text = folder;

            btnParse.Visible = true;
        }
    }

    private void btnParse_Click(object sender, EventArgs e)
    {
        btnParse.Visible = false;

        lbProcessedFiles.Visible = true;
        pbFilesProcessed.Visible = true;
        lbProcessedLines.Visible = true;
        pbLinesProcessed.Visible = true;
        lbProcessedLines.Text = "Lines: 0 / 0";

        int fileCount = 1;

        foreach (var csvFile in Directory.GetFiles(folderBrowserDialog1.SelectedPath))
        {
            pbFilesProcessed.Maximum = Convert.ToInt32(files.Length.ToString());

            string fileName = "Waveforms.csv";

            int lineCount = 0;

            string lines;

            string newLines;              

            string csvFullFilePath = csvFile.ToString();
            string[] filePathSplit = csvFullFilePath.Split('\\');
            string pointName = filePathSplit[4].ToString();

            string[] pathDirectionSplit = filePathSplit[5].ToString().Split('_');
            string[] swingDirectionSplit = pathDirectionSplit[3].Split('.');
            string swingDirection = swingDirectionSplit[0];


            var numberOfLines = File.ReadLines(csvFile).Count();

            using (StreamReader r = new StreamReader(csvFile))
            {
                while ((lines = r.ReadLine()) != null)
                {
                    pbLinesProcessed.Maximum = Convert.ToInt32(numberOfLines.ToString());

                    if (lineCount == 0)
                    {
                        lines.Remove(0);
                        lineCount++;
                    }
                    else
                    {
                        newLines = Regex.Replace(lines, ",{2,}", ",").ToString();
                        File.AppendAllText(@"Simulator\\" + fileName, pointName + "," + swingDirection + "," + newLines + System.Environment.NewLine);

                        pbLinesProcessed.PerformStep();
                        lbProcessedLines.Text = "Lines: " + lineCount + "/" + Convert.ToInt32(numberOfLines.ToString()); 

                        lineCount++;                                  
                    }
                }
                r.Close();
            }
            pbFilesProcessed.PerformStep();
            lbProcessedFiles.Text = "Files: " + fileCount.ToString() + "/" + files.Length.ToString();
            fileCount++;
        }
        btnParse.Visible = false;
        MessageBox.Show("Done");
    }  
}

} }

Right, after an hour or so, this is what i have done. 对,大约一个小时后,这就是我所做的。 not the most elegant as im still a novice Thanks to nim (MSDN Link). 由于nim(MSDN Link),所以不是最优雅的即时消息仍然是新手。 However i am having trouble getting the correct amount of progress shown on the progressbar..... 但是我无法获得进度条上显示的正确进度量.....

namespace myParser
{
public partial class Form1 : Form
{
    string filePath;
    string[] files;
    int fileCount = 0;
    int numberOfFiles;
    int lineCount = 0;
    int numberOfLines;

    public Form1()
    {
        InitializeComponent();

        pbFilesProcessed.Visible = false;
        pbLinesProcessed.Visible = false;
        btnParse.Visible = false;
        lbProcessedFiles.Visible = false;
        lbProcessedLines.Visible = false;
    }

    private void btnOpen_Click(object sender, EventArgs e)
    {
        DialogResult result = folderBrowserDialog1.ShowDialog();
        if (result == DialogResult.OK)
        {
            //counts the number of files in the folder
            files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);

            filePath = folderBrowserDialog1.SelectedPath.ToString();

            char[] delimiterChars = { '\\' };
            string[] filePathParts = filePath.Split(delimiterChars);

            string folder = filePathParts[4];

            tbFolderName.Text = folder;

            btnParse.Visible = true;
        }
    }

    private void btnParse_Click(object sender, EventArgs e)
    {
        btnParse.Visible = false;
        btnOpen.Visible = false;

        lbProcessedFiles.Visible = true;
        pbFilesProcessed.Visible = true;
        lbProcessedLines.Visible = true;
        pbLinesProcessed.Visible = true;
        lbProcessedLines.Text = "Lines: 0 / 0";

        pbFilesProcessed.Maximum = Convert.ToInt32(files.Length.ToString());

        backgroundWorker1.RunWorkerAsync();
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {

        foreach (var csvFile in Directory.GetFiles(folderBrowserDialog1.SelectedPath))
        {
            numberOfFiles = Convert.ToInt32(files.Length.ToString());

            string fileName = "Waveforms.csv";
            lineCount = 0;
            string lines;
            string newLines;
            string csvFullFilePath = csvFile.ToString();
            string[] filePathSplit = csvFullFilePath.Split('\\');
            string pointName = filePathSplit[4].ToString();
            string[] pathDirectionSplit = filePathSplit[5].ToString().Split('_');
            string[] swingDirectionSplit = pathDirectionSplit[3].Split('.');
            string swingDirection = swingDirectionSplit[0];

            numberOfLines = File.ReadLines(csvFile).Count();

            using (StreamReader r = new StreamReader(csvFile))
            {
                while ((lines = r.ReadLine()) != null)
                {
                    if (lineCount == 0)
                    {
                        lines.Remove(0);
                        lineCount++;
                    }
                    else
                    {
                        newLines = Regex.Replace(lines, ",{2,}", ",").ToString();
                        File.AppendAllText(@"Simulator\\" + fileName, pointName + "," + swingDirection + "," + newLines + System.Environment.NewLine);
                        backgroundWorker1.ReportProgress(lineCount);
                        lineCount++;
                    }
                }
                r.Close();
            }
            backgroundWorker1.ReportProgress(fileCount);
            fileCount++;
        }
    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        pbFilesProcessed.PerformStep();
        lbProcessedFiles.Text = "Files: " + fileCount.ToString() + "/" + files.Length.ToString();
        pbLinesProcessed.PerformStep();
        lbProcessedLines.Text = "Lines: " + lineCount + "/" + Convert.ToInt32(numberOfLines.ToString());
    }

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        btnParse.Visible = false;
        MessageBox.Show("Done");
        btnOpen.Visible = true;
    }  
}

} }

Please refer to MSDN documentation on BackgroundWorker 请参考BackgroundWorker上的MSDN文档

There is a very short but good sample code near bottom of the page. 页面底部附近有一个很短但很好的示例代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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