Ajit N

Ajit N

  • NA
  • 352
  • 71.2k

How to rename a file when it is already exist in a folder ?

Jan 18 2017 6:42 AM
Hi, In desktop application i saving the images in folders but when i save the images second time it will overwrite. so i want to save the same images in folder with rename like Picture(1).jpg.
so please help me how can i do this.
i tried the following code but images with numbers are not incremented.
  1. string folderPath1 = "E:\\CoachingClassImages\\HeaderInfoImages\\Logo\\";  
  2.                 if (!Directory.Exists(folderPath1))  
  3.                 {  
  4.                     Directory.CreateDirectory(folderPath1);  
  5.                 }  
  6.   
  7.   
  8.                 //Save the file in folder  
  9.                 int count = 1;  
  10.                 string file = "E:\\CoachingClassImages\\HeaderInfoImages\\Logo\\" + logo_picname;  
  11.                 string filename = Path.GetFileNameWithoutExtension(logo_location);  
  12.                 string extention = Path.GetExtension(filename);  
  13.                 string fileLocation1 = file;  
  14.                 if (File.Exists(file))  
  15.                 {  
  16.                     System.GC.Collect();  
  17.                     System.GC.WaitForPendingFinalizers();  
  18.   
  19.                     string tempFileName = string.Format("{0}({1}){2}", filename, count++, extention);  
  20.   
  21.                     File.Copy(fileLocation1, Path.Combine("E:\\CoachingClassImages\\HeaderInfoImages\\Logo\\", Path.GetFileName(tempFileName)), true);  
  22.                 }  
  23.                 else  
  24.                 {  
  25.                     File.Copy(fileLocation1, Path.Combine("E:\\CoachingClassImages\\HeaderInfoImages\\Logo\\", Path.GetFileName(filename)), true);  
  26.                 } 
 
 

Answers (3)