gpt4 book ai didi

c# - 去掉文件名中的*连续*句点

转载 作者:行者123 更新时间:2023-11-30 18:49:06 24 4
gpt4 key购买 nike

我想知道如果我有这样的文件名,我如何去掉文件名中的句点:

Test....1.txt 看起来像 Test 1.txt?我不希望像 1.0.1 Test.txt 这样的文件被触及。只有具有连续句点的文件才应该用空格替换。有什么想法吗?

这是我当前的代码,但如您所见,它替换了扩展名中除句点之外的所有句点:

 public void DoublepCleanUp(List<string> doublepFiles)
{
Regex regExPattern2 = new Regex(@"\s{2,}");
Regex regExPattern4 = new Regex(@"\.+");
Regex regExPattern3 = new Regex(@"\.(?=.*\.)");
string replace = " ";
List<string> doublep = new List<string>();
var filesCount = new Dictionary<string, int>();

try
{
foreach (string invalidFiles in doublepFiles)
{
string fileOnly = System.IO.Path.GetFileName(invalidFiles);
string pathOnly = System.IO.Path.GetDirectoryName(fileOnly);

if (!System.IO.File.Exists(fileOnly))
{
string filewithDoublePName = System.IO.Path.GetFileName(invalidFiles);
string doublepPath = System.IO.Path.GetDirectoryName(invalidFiles);
string name = System.IO.Path.GetFileNameWithoutExtension(invalidFiles);
//string newName = name.Replace(".", " ");
string newName = regExPattern4.Replace(name, replace);
string newName2 = regExPattern2.Replace(newName, replace);
string filesDir = System.IO.Path.GetDirectoryName(invalidFiles);
string fileExt = System.IO.Path.GetExtension(invalidFiles);
string fileWithExt = newName2 + fileExt;
string newPath = System.IO.Path.Combine(filesDir, fileWithExt);
System.IO.File.Move(invalidFiles, newPath);


DataGridViewRow clean = new DataGridViewRow();
clean.CreateCells(dataGridView1);
clean.Cells[0].Value = doublepPath;
clean.Cells[1].Value = filewithDoublePName;
clean.Cells[2].Value = fileWithExt;
dataGridView1.Rows.Add(clean);
}

else
{
if (filesCount.ContainsKey(fileOnly))
{
filesCount[fileOnly]++;
}
else
{
filesCount.Add(fileOnly, 1);
string newFileName = String.Format("{0}{1}{2}",
System.IO.Path.GetFileNameWithoutExtension(fileOnly),
filesCount[fileOnly].ToString(),
System.IO.Path.GetExtension(fileOnly));

string newFilePath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(fileOnly), newFileName);
System.IO.File.Move(fileOnly, newFilePath);

DataGridViewRow clean = new DataGridViewRow();
clean.CreateCells(dataGridView1);
clean.Cells[0].Value = pathOnly;
clean.Cells[1].Value = fileOnly;
clean.Cells[2].Value = newFileName;
dataGridView1.Rows.Add(clean);
}

}
}
}
catch(Exception e)
{
//throw;
StreamWriter doublepcleanup = new StreamWriter(@"G:\DoublePeriodCleanup_Errors.txt");
doublepcleanup.Write("Double Period Error: " + e + "\r\n");
doublepcleanup.Close();
}

}

最佳答案

string name = "Text...1.txt";   
Regex r = new Regex("[.][.]+");
string result = r.Replace(name, " ");

关于c# - 去掉文件名中的*连续*句点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3390288/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com