C# 当图像已经存在于文件夹中时,如何重命名图像?
我正在开发桌面应用程序。在这种情况下,我想保存在重命名文件夹中的图像。如果文件夹中的图像是Img.jpg,那么下次图像将是Img1.jpg。我尝试了一些代码,但没有得到结果 这是我的密码C# 当图像已经存在于文件夹中时,如何重命名图像?,c#,asp.net,winforms,sql-server-2008,C#,Asp.net,Winforms,Sql Server 2008,我正在开发桌面应用程序。在这种情况下,我想保存在重命名文件夹中的图像。如果文件夹中的图像是Img.jpg,那么下次图像将是Img1.jpg。我尝试了一些代码,但没有得到结果 这是我的密码 string folderPath1 = "E:\\CoachingClassImages\\HeaderInfoImages\\Logo"; if (!Directory.Exists(folderPath1)) { Directory.CreateDirectory(folderPath1); }
string folderPath1 = "E:\\CoachingClassImages\\HeaderInfoImages\\Logo";
if (!Directory.Exists(folderPath1))
{
Directory.CreateDirectory(folderPath1);
}
//Save the file in folder
int count = 1;
string file = "E:\\CoachingClassImages\\HeaderInfoImages\\Logo" + logo_picname;
string extention=Path.GetExtension("jpeg|*.jpg|bmp|*.bmp|all files|*.*");
string fileLocation1 = file;
if (File.Exists(file))
{
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
string tempFileName = string.Format("{0}({1}){2}", logo_picname, extention, count++);
File.Copy(fileLocation1, Path.Combine("E:\\CoachingClassImages\\HeaderInfoImages\\Logo", Path.GetFileName(tempFileName)), true);
}
else
{
File.Copy(fileLocation1, Path.Combine("E:\\CoachingClassImages\\HeaderInfoImages\\Logo", Path.GetFileName(logo_location)), true);
}
问题在于文件名,在您的情况下,您是按照
logo\u picname
-扩展名
-计数
的顺序指定值,这将生成文件名为Img(.jpg)3
。这是因为String.Format`遵循从零开始的索引。必须按要求的顺序指定参数。还有一件事我没有得到你想要的文件扩展名,不管怎样,源文件和目标文件的扩展名应该是相同的,所以你应该从源文件获得扩展名
所以你应该这样使用:
string file = "E:\\CoachingClassImages\\HeaderInfoImages\\Logo" + logo_picname;
string extention=Path.GetExtension(file);
string tempFileName = string.Format("{0}({1}){2}", logo_picname,count++, extention);
// will give you the file name as Img(3).jpg if count is 3
使用逻辑
1.Select all the String that has name (Img).
2.First of all you have to create an array (String myList[];) that will take all the file named (Img) existing in the folder . and then
take lenght for myList.Lenght();
3. again create an array an do this For (int i =0;i<myList.Lenght();i++ ){ String myNew[i]=myList[i].getText().replaceAll("\\D+","");`enter code here`
}
不幸的是,先生,我再次在扩展变量中遇到错误,如“非法字符串”。@Ajitinmbalkar:查看更新的答案,如果您需要任何澄清,请告诉我这是字符串。我想用图片来说明这个扩展。这就是我为什么要这么做的原因。@不幸的先生,同样的图像不会随着数字而递增。@Ajitinbulkar:那么那里发生了什么?你检查过断点了吗
4.When u got the array with numbers take Lenght(); of that array
5.Finally when u r creating a new file call this funtion and get the number on files in the folder which has same name and Lenght()+1 and
U are Done !
**I Hope You Will Understand my Logic . :)**