我有一个应用程序,用空格替换“无效”字符(由我的正则表达式定义)。我想要它,以便如果文件名中有两个或更多个空格,请修剪一个。例如:正则表达式 - 摆脱双空白?
Deal A & B.txt
我的应用程序运行后,将被重命名为Deal A B.txt
(3个空间B/W 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();
}
}
的问题是,一个重命名后,不是所有的文件将具有blankspaces相同数量。如在,我可以有Deal A&B.txt
其中重命名后将成为Deal A B.txt
(1空间B /瓦A和B - 这很好)。但我也将有如下文件:Deal A & B & C.txt
重命名后:Deal A B C.txt
(A,B和C之间3个空格 - 不可接受)。
有没有人有任何想法/代码如何做到这一点?
这是否需要一个新的foreach循环后,我完成了“消毒”文件? – yeahumok 2010-07-09 15:06:32
@yeahumok请参阅我上面的修改。如果你现有的循环,只需在第一个之后添加第二个正则表达式。 – CodingWithSpike 2010-07-09 15:16:04
非常感谢你!这工作,它完全有道理:)我感谢您的帮助! – yeahumok 2010-07-09 15:33:02