我想将文件复制到目录并重命名为特定格式。但如果文件名已存在,则应在文件扩展名前附加{1},{2}或{3}。
我的代码重命名并复制了文件,并将其命名为我想要的格式,例如filename.pdf,当它检查重复时,将其重命名为filename1.pdf。但是当它再次尝试复制时,它给出了一个错误“文件已存在”,但我希望它将其命名为filename02.pdf。
是的,有人可以帮助我。这是我到目前为止编写的代码。
{
string fileSource, filesToCopy, target, nextTarget;
string sourceDir = @"C:\HCP_PDFs";
string destinationDir = @"C:\RenamedHcpPdfs";
DirectoryInfo di = new DirectoryInfo(destinationDir);
// create the directory if it dosnt exist
if (!Directory.Exists(destinationDir))
{
Directory.CreateDirectory(destinationDir);
}
foreach (string myFiles in lstBoxFilenames.Items)
{
filesToCopy = myFiles;
fileSource = Path.Combine(sourceDir, filesToCopy);
//Extract only HCP Name by splitting , removing file Extension and removing HCP ID
string hcp = filesToCopy.Split('_')[0];
string hcpCd = filesToCopy.Split('_')[1];
string hcpID = filesToCopy.Split('_')[2];
string hcpName = String.Format((filesToCopy.Split('_')[3]).Replace(".pdf", ""));
//combine the HCP ID, HCP name and date
target = Path.Combine(destinationDir, hcp + "{" + hcpCd + "~" + hcpID + "}" + hcpName + "{2013_03_14}" + ".pdf");
// if file exists in directory then rename and increment filename by 1
int i = +1 ;
nextTarget = Path.Combine(destinationDir, hcp + "{" + hcpCd + "~" + hcpID + "}" + hcpName + "{2013_03_14}" + i + ".pdf");
if (File.Exists(target))
{
File.Copy(fileSource, nextTarget);
break;
}
//if file does not exist, rename
else
{
File.Copy(fileSource, target);
}
}
}
答案 0 :(得分:0)
这样做
而(File.Exists(目标)) {I ++;}
现在声明您的目标路径。
答案 1 :(得分:0)
试试这个:
string target = Path.Combine(destinationDir, hcp + "{" + hcpCd + "~" + hcpID + "}" + hcpName + "{2013_03_14}.pdf");
while(File.Exists(target))
{
i++;
target = Path.Combine(destinationDir, hcp + "{" + hcpCd + "~" + hcpID + "}" + hcpName + "{2013_03_14}" + i + ".pdf");
}
File.Copy(fileSource, target);
break;