关于 Giuseppe 对 windows 重命名文件方式的评论,我在一个版本上工作,该版本在文件名中找到任何现有索引,即 (2),并根据 windows 相应地重命名文件。假定 sourceFileName 有效,并且此时假定用户对目标文件夹具有写权限:
using System.IO;
using System.Text.RegularExpressions;
private void RenameDiskFileToMSUnique(string sourceFileName)
{
string destFileName = "";
long n = 1;
// ensure the full path is qualified
if (!Path.IsPathRooted(sourceFileName)) { sourceFileName = Path.GetFullPath(sourceFileName); }
string filepath = Path.GetDirectoryName(sourceFileName);
string fileNameWOExt = Path.GetFileNameWithoutExtension(sourceFileName);
string fileNameSuffix = "";
string fileNameExt = Path.GetExtension(sourceFileName);
// if the name includes the text "(0-9)" then we have a filename, instance number and suffix
Regex r = new Regex(@"\(\d+\)");
Match match = r.Match(fileNameWOExt);
if (match.Success) // the pattern (0-9) was found
{
// text after the match
if (fileNameWOExt.Length > match.Index + match.Length) // remove the format and create the suffix
{
fileNameSuffix = fileNameWOExt.Substring(match.Index + match.Length, fileNameWOExt.Length - (match.Index + match.Length));
fileNameWOExt = fileNameWOExt.Substring(0, match.Index);
}
else // remove the format at the end
{
fileNameWOExt = fileNameWOExt.Substring(0, fileNameWOExt.Length - match.Length);
}
// increment the numeric in the name
n = Convert.ToInt64(match.Value.Substring(1, match.Length - 2)) + 1;
}
// format variation: indexed text retains the original layout, new suffixed text inserts a space!
do
{
if (match.Success) // the text was already indexed
{
if (fileNameSuffix.Length > 0)
{
destFileName = Path.Combine(filepath, String.Format("{0}({1}){2}{3}", fileNameWOExt, (n++), fileNameSuffix, fileNameExt));
}
else
{
destFileName = Path.Combine(filepath, String.Format("{0}({1}){2}", fileNameWOExt, (n++), fileNameExt));
}
}
else // we are adding a new index
{
destFileName = Path.Combine(filepath, String.Format("{0} ({1}){2}", fileNameWOExt, (n++), fileNameExt));
}
}
while (File.Exists(destFileName));
File.Copy(sourceFileName, destFileName);
}