У меня есть приложение, которое заменяет «недопустимые» символы (как определено моим Regex) пробелом.Я хочу, чтобы, если в имени файла было 2 или более пробелов, обрезать один.Например:
Deal A & B.txt
после запуска моего приложения будет переименовано в Deal A B.txt
(3 пробела ч / б A и B).Что я действительно хочу, так это: Deal A B.txt
(один пробел между A и B).
Я пытаюсь определить, как это сделать - я полагаю, что моему приложению придется хотя бы один раз выполнить все имена файлов, чтобы заменить недопустимые символы, а затем снова запустить имена файлов, чтобы избавиться от лишних пробелов.
Кто-нибудь может мне помочь с этим?
Вот мой код для замены недопустимых символов:
public partial class CleanNames : Form
{
public CleanNames()
{
InitializeComponent();
}
public void Sanitizer(List<string> paths)
{
string regPattern = (@"[~#&$!%+{}]+");
string replacement = " ";
Regex regExPattern = new Regex(regPattern);
StreamWriter errors = new StreamWriter(@"S:\Testing\Errors.txt", true);
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);
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);
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);
}
}
}
catch (Exception e)
{
errors.Write(e);
}
}
private void SanitizeFileNames_Load(object sender, EventArgs e)
{ }
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
Проблема в том, что не все файлы после переименования будут иметьтакое же количество пробелов.Например, у меня может быть Deal A&B.txt
, который после переименования станет Deal A B.txt
(1 пробел ч / б A и B - это нормально).Но у меня также будут файлы, подобные: Deal A & B & C.txt
, который после переименования будет: Deal A B C.txt
(3 пробела между A, B и C - недопустимы).
У кого-нибудь есть идеи / код для того, как этого добиться?