I am trying to take file names that look like this:
MAX_1.01.01.03.pdf look like Max_1010103.pdf.
I currently have this code:
public void Sanitizer(List<string> paths) { string regPattern = (@"[~#&!%+{}]+"); string replacement = " "; Regex regExPattern = new Regex(regPattern); Regex regExPattern2 = new Regex(@"\s{2,}"); Regex regExPattern3 = new Regex(@"\.(?=.*\.)"); string replace = ""; var filesCount = new Dictionary<string, int>(); dataGridView1.Rows.Clear(); try { foreach (string files2 in paths) { string filenameOnly = System.IO.Path.GetFileName(files2); string pathOnly = System.IO.Path.GetDirectoryName(files2); string sanitizedFileName = regExPattern.Replace(filenameOnly, replacement); sanitizedFileName = regExPattern2.Replace(sanitizedFileName, replacement); string sanitized = System.IO.Path.Combine(pathOnly, sanitizedFileName); if (!System.IO.File.Exists(sanitized)) { DataGridViewRow clean = new DataGridViewRow(); clean.CreateCells(dataGridView1); clean.Cells[0].Value = pathOnly; clean.Cells[1].Value = filenameOnly; clean.Cells[2].Value = sanitizedFileName; dataGridView1.Rows.Add(clean); System.IO.File.Move(files2, sanitized); } else { if (filesCount.ContainsKey(sanitized)) { filesCount[sanitized]++; } else { filesCount.Add(sanitized, 1); string newFileName = String.Format("{0}{1}{2}", System.IO.Path.GetFileNameWithoutExtension(sanitized), filesCount[sanitized].ToString(), System.IO.Path.GetExtension(sanitized)); string newFilePath = System.IO.Path.Combine( System.IO.Path.GetDirectoryName(sanitized), newFileName); newFileName = regExPattern2.Replace(newFileName, replacement); System.IO.File.Move(files2, newFilePath); sanitized = newFileName; DataGridViewRow clean = new DataGridViewRow(); clean.CreateCells(dataGridView1); clean.Cells[0].Value = pathOnly; clean.Cells[1].Value = filenameOnly; clean.Cells[2].Value = newFileName; dataGridView1.Rows.Add(clean); }
I ran this and instead of getting rid of the TOTAL period (minus the period before the file extension), I get results such as: MAX_1.0103.pdf
If there are several periods like: Test....1.txt , I get the following results: Test...1.txt
It seems that he gets rid of only ONE period. I am new to regular expressions and this is REQUIREMENT for this project. Can someone help me figure out what I'm doing wrong here?
Thanks!
EDITED to show changes made to code
source share