F
fosfik
Guest
I have code to find and replace based on text area to multiple files (loop). I woudl like to change find to find everything between <variables></variables>. Theres a lot xml files and they have random text after <variables>. App work fine to search exactly what i paste in to the field and change it in all files.
Now I have winform System.Windows.Forms.TextBox to find text. How I can change it all to find only all between tags?
I know I can use regex match (?<=<variables>).+?(?=</variables>) but I don't know how.
public partial class FindReplaceForm : Form
{
private string outputDirectory;
private string findWhatString;
private string replaceWithText;
private bool isMatchWholeWord;
private bool isMatchCase;
private bool isWildcard;
public FindReplaceForm()
{
InitializeComponent();
}
private int DoFindReplace(BackgroundWorker worker)
{
int filesAffectedCount = 0;
int counter = 0;
string[] filesInDirectory = Directory.GetFiles(outputDirectory, "*.xml");
int totalFiles = filesInDirectory.GetLength(0);
foreach (string file in filesInDirectory)
{
if (FindAndReplace(file))
{
filesAffectedCount++;
}
counter++;
worker.ReportProgress((int)((counter / totalFiles) * 100.00));
}
return filesAffectedCount;
}
private bool FindAndReplace(string file)
{
string content = string.Empty;
using (StreamReader sr = new StreamReader(file))
{
content = sr.ReadToEnd();
}
string searchText = GetSearchText(findWhatString);
if (Regex.IsMatch(content, searchText, GetRegExOptions()))
{
string newText = Regex.Replace(content, searchText, replaceWithText, GetRegExOptions());
using (StreamWriter sw = new StreamWriter(file))
{
sw.Write(newText);
}
return true;
}
return false;
}
private RegexOptions GetRegExOptions()
{
RegexOptions options = new RegexOptions();
if (isMatchCase == false)
options |= RegexOptions.IgnoreCase;
return options;
}
private string GetSearchText(string textToFind)
{
string searchText = Regex.Escape(textToFind);
if (isMatchWholeWord)
{
searchText = string.Format("{0}{1}{0}", @"\b", textToFind);
}
if (isWildcard)
{
searchText = searchText.Replace(@"\*", ".*").Replace(@"\?", ".");
}
return searchText;
}
private void InitializeProcess()
{
outputDirectory = txtDirectory.Text;
findWhatString = txtFindWhat.Text;
replaceWithText = txtReplaceWith2.Text;
isWildcard = chkUseWildcards.Checked;
isMatchCase = chkMatchCase.Checked;
isMatchWholeWord = chkMatchWholeWord.Checked;
statusLabel.Text = "Pracuje...";
progressBar.Value = 0;
progressBar.Visible = true;
btnReplace.Enabled = false;
btnCancel.Enabled = true;
backgroundWorker.RunWorkerAsync();
}
private void DeinitializeProcess()
{
statusLabel.Text = "Gotowy";
progressBar.Visible = false;
btnReplace.Enabled = true;
btnCancel.Enabled = false;
}
private void BrowseDirectory()
{
FolderBrowserDialog browser = new FolderBrowserDialog();
if (browser.ShowDialog(this) == DialogResult.OK)
{
txtDirectory.Text = browser.SelectedPath;
}
}
private bool InputIsValid()
{
bool isError = false;
errorProvider.Clear();
if (string.IsNullOrEmpty(txtFindWhat.Text))
{
errorProvider.SetError(txtFindWhat, "This is a required field.");
isError = true;
}
if (string.IsNullOrEmpty(txtReplaceWith2.Text))
{
errorProvider.SetError(txtReplaceWith2, "This is a required field.");
isError = true;
}
if (string.IsNullOrEmpty(txtDirectory.Text))
{
errorProvider.SetError(txtDirectory, "This is a required field.");
isError = true;
}
else
{
if (Directory.Exists(txtDirectory.Text) == false)
{
errorProvider.SetError(txtDirectory, "The selected directory does not exist.");
isError = true;
}
}
if (isError)
return false;
else
return true;
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
e.Result = (int)DoFindReplace(worker);
}
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
DeinitializeProcess();
if (e.Error != null)
MessageBox.Show(this, e.Error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
else if (e.Cancelled)
MessageBox.Show(this, "Operacja przerwana przez użytkownika", "Anulowano.", MessageBoxButtons.OK, MessageBoxIcon.Error);
else
MessageBox.Show(this, string.Format("{0} plików zostało nadpisanych.", e.Result.ToString()), "Zamiana zakończona!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void btnReplace_Click(object sender, EventArgs e)
{
if (InputIsValid())
InitializeProcess();
}
private void lnkBrowse_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
BrowseDirectory();
}
}
}
Continue reading...
Now I have winform System.Windows.Forms.TextBox to find text. How I can change it all to find only all between tags?
I know I can use regex match (?<=<variables>).+?(?=</variables>) but I don't know how.
public partial class FindReplaceForm : Form
{
private string outputDirectory;
private string findWhatString;
private string replaceWithText;
private bool isMatchWholeWord;
private bool isMatchCase;
private bool isWildcard;
public FindReplaceForm()
{
InitializeComponent();
}
private int DoFindReplace(BackgroundWorker worker)
{
int filesAffectedCount = 0;
int counter = 0;
string[] filesInDirectory = Directory.GetFiles(outputDirectory, "*.xml");
int totalFiles = filesInDirectory.GetLength(0);
foreach (string file in filesInDirectory)
{
if (FindAndReplace(file))
{
filesAffectedCount++;
}
counter++;
worker.ReportProgress((int)((counter / totalFiles) * 100.00));
}
return filesAffectedCount;
}
private bool FindAndReplace(string file)
{
string content = string.Empty;
using (StreamReader sr = new StreamReader(file))
{
content = sr.ReadToEnd();
}
string searchText = GetSearchText(findWhatString);
if (Regex.IsMatch(content, searchText, GetRegExOptions()))
{
string newText = Regex.Replace(content, searchText, replaceWithText, GetRegExOptions());
using (StreamWriter sw = new StreamWriter(file))
{
sw.Write(newText);
}
return true;
}
return false;
}
private RegexOptions GetRegExOptions()
{
RegexOptions options = new RegexOptions();
if (isMatchCase == false)
options |= RegexOptions.IgnoreCase;
return options;
}
private string GetSearchText(string textToFind)
{
string searchText = Regex.Escape(textToFind);
if (isMatchWholeWord)
{
searchText = string.Format("{0}{1}{0}", @"\b", textToFind);
}
if (isWildcard)
{
searchText = searchText.Replace(@"\*", ".*").Replace(@"\?", ".");
}
return searchText;
}
private void InitializeProcess()
{
outputDirectory = txtDirectory.Text;
findWhatString = txtFindWhat.Text;
replaceWithText = txtReplaceWith2.Text;
isWildcard = chkUseWildcards.Checked;
isMatchCase = chkMatchCase.Checked;
isMatchWholeWord = chkMatchWholeWord.Checked;
statusLabel.Text = "Pracuje...";
progressBar.Value = 0;
progressBar.Visible = true;
btnReplace.Enabled = false;
btnCancel.Enabled = true;
backgroundWorker.RunWorkerAsync();
}
private void DeinitializeProcess()
{
statusLabel.Text = "Gotowy";
progressBar.Visible = false;
btnReplace.Enabled = true;
btnCancel.Enabled = false;
}
private void BrowseDirectory()
{
FolderBrowserDialog browser = new FolderBrowserDialog();
if (browser.ShowDialog(this) == DialogResult.OK)
{
txtDirectory.Text = browser.SelectedPath;
}
}
private bool InputIsValid()
{
bool isError = false;
errorProvider.Clear();
if (string.IsNullOrEmpty(txtFindWhat.Text))
{
errorProvider.SetError(txtFindWhat, "This is a required field.");
isError = true;
}
if (string.IsNullOrEmpty(txtReplaceWith2.Text))
{
errorProvider.SetError(txtReplaceWith2, "This is a required field.");
isError = true;
}
if (string.IsNullOrEmpty(txtDirectory.Text))
{
errorProvider.SetError(txtDirectory, "This is a required field.");
isError = true;
}
else
{
if (Directory.Exists(txtDirectory.Text) == false)
{
errorProvider.SetError(txtDirectory, "The selected directory does not exist.");
isError = true;
}
}
if (isError)
return false;
else
return true;
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
e.Result = (int)DoFindReplace(worker);
}
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
DeinitializeProcess();
if (e.Error != null)
MessageBox.Show(this, e.Error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
else if (e.Cancelled)
MessageBox.Show(this, "Operacja przerwana przez użytkownika", "Anulowano.", MessageBoxButtons.OK, MessageBoxIcon.Error);
else
MessageBox.Show(this, string.Format("{0} plików zostało nadpisanych.", e.Result.ToString()), "Zamiana zakończona!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void btnReplace_Click(object sender, EventArgs e)
{
if (InputIsValid())
InitializeProcess();
}
private void lnkBrowse_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
BrowseDirectory();
}
}
}
Continue reading...