Tuesday, December 4, 2018

Replace a file with a datatable

 private void BtnExecute_Click(object sender, EventArgs e)
        {
            if (txtDictionary.Text != "" && txtTarget.Text != "")
            {
                string newPath = Path.GetFullPath(Path.Combine(txtTarget.Text, @"..\"));//to go back from current directory
                string filename = Path.GetFileName(txtTarget.Text); //to get the filename
                try
                {
                    System.Data.DataTable dtDictionary = new System.Data.DataTable();
                    dtDictionary = ReadExcel(txtDictionary.Text);

                    if (dtDictionary.Columns.Count == 2)
                    {
                        System.IO.Directory.CreateDirectory(newPath + "ReplacedTarget"); // To create folder if it doesn't exists                     
                        string fileExt = Path.GetExtension(txtTarget.Text); //get the file extension 
                        double totalCount = 0;
                        File.Copy(txtTarget.Text, newPath + "\\ReplacedTarget\\" + filename); //copying target file

                     
                            for (int i = 0; i < dtDictionary.Rows.Count; i++)
                            {
                                if (dtDictionary.Rows[i].ItemArray[0].ToString().Trim() != "")
                                {
                                    int cnt = 0;
                                    try
                                    {
                                        string pattern = string.Format(@"\b{0}\b", dtDictionary.Rows[i].ItemArray[0].ToString().Trim());//to replace the whole word instead of part of a word

                                        if (chkCase.Checked == true)
                                        {
                                            //To get the matched words count in dictionary and target
                                            cnt = Regex.Matches(File.ReadAllText(txtTarget.Text), pattern).Count;
                                            if (cnt > 0)
                                            {
                                                //To replace matched words
                                                File.WriteAllText(newPath + "ReplacedTarget\\" + filename, File.ReadAllText(newPath + "ReplacedTarget\\" + filename).Replace(pattern, dtDictionary.Rows[i].ItemArray[1].ToString()));
                                            }
                                        }
                                        else
                                        {
                                            //To get the matched words count in dictionary and target irrespective of case
                                            cnt = Regex.Matches(File.ReadAllText(txtTarget.Text), pattern, RegexOptions.IgnoreCase).Count;

                                            if (cnt > 0)
                                            {
                                                //To replace matched words irrespective of case
                                                File.WriteAllText(newPath + "ReplacedTarget\\" + filename, Regex.Replace(File.ReadAllText(newPath + "ReplacedTarget\\" + filename), pattern, dtDictionary.Rows[i].ItemArray[1].ToString(), RegexOptions.IgnoreCase));
                                                Log.WriteLog(Path.GetFileName(txtTarget.Text) + " target file replaced with " + Path.GetFileName(txtDictionary.Text) + " : Replaced " + cnt + " entries from " + dtDictionary.Rows[i].ItemArray[0].ToString() + " to " + dtDictionary.Rows[i].ItemArray[1].ToString());
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        cnt = 0;
                                        Log.WriteLog("BtnExecute_Click at WriteAllText" + ex.Message);
                                        MessageBox.Show(ex.Message);
                                    }
                                    //for total matched words in the file
                                    totalCount = totalCount + cnt;
                                }
                            }
                   
                        btnExecute.Enabled = false;
                        if (totalCount == 0)
                        {
                            File.Delete(newPath + "\\ReplacedTarget\\" + filename);
                        }

                        MessageBox.Show(totalCount + " total replacements completed");
                        Log.WriteLog(Path.GetFileName(txtTarget.Text) + " target file replaced with " + Path.GetFileName(txtDictionary.Text) + " : " + totalCount + " total replacements completed.\n");
                    }
                    else
                    {
                        MessageBox.Show("The excel sheet columns are not 2, Please select exact one.");
                        Log.WriteLog(Path.GetFileName(txtDictionary.Text) + " excel sheet columns are not 2, Please select exact one.");
                    }
                }
                catch (Exception ex)
                {
                    Log.WriteLog("BtnExecute_Click" + ex.Message);
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    foreach (Process process in Process.GetProcesses())
                    {
                        if (process.MainWindowTitle.Contains(txtDictionary.Text) || process.MainWindowTitle.Contains(txtTarget.Text))
                        {
                            process.Kill();
                            break;
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("please select Dictionary/Target files to proceed");
                Log.WriteLog("please select Dictionary/Target files to proceed");
            }
        }

No comments:

Post a Comment