我有去的,取代了"无效"字符(由我正则表达式定义)与blankspace的应用程序.我想要它,以便如果文件名中有2个或更多空格,则修剪一个.例如:
Deal A & B.txt在我的应用程序运行后,将重命名为Deal A B.txt(3个空格b/w A和B).我想要的是这样的:( Deal A B.txtA和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();
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,重命名后并非所有文件都具有相同数量的空白.作中,我可以有Deal A&B.txt它的重命名后会成为Deal A B.txt(1个空间的B/W A和B -这是好的).但我也将具有像文件: Deal A & B & C.txt其中重命名后为:Deal A B C.txt(A,B和C之间3位-不能接受).
有没有人有任何想法/代码如何实现这一目标?
| 归档时间: |
|
| 查看次数: |
651 次 |
| 最近记录: |