I am beginner in c#. In my project, the user selects a Image file through OpenFileDialog box. When he/she selects the image file I am running the back code something like this:
File.Copy(SourceFilePath, DestinationFilePath);
The problem with the above code is that it is throwing error whenever the user is trying to add a existing image file. To avoid this error, I changed my code to the below one:
if (File.Exists(DestinationFilePath))
{
intCount++;
File.Copy(SourceFilePath,TemporaryFilePath);
File.Copy(TemporaryFilePath, DestinationFilePath + intCount.ToString());
File.Delete(TemporaryFilePath);
}
else
{
File.Copy(SourceFilePath, DestinationFilePath);
}
The problem in the above code is that it is adding the intCount value at the very end of the image file like image.gif1 which is changing the file extension. How to add a counter to image file paths?
And I think the approach I am using here to check the existing file is not correct way of doing.
Update: Answer :-
int intCount = 1;
while (File.Exists(Application.StartupPath + DirectoryPath + strPath))
{
strPath = Path.GetFileNameWithoutExtension(strPath) + intLarge.ToString() + Path.GetExtension(strPath);
intCount++;
}
intCount = 1;
use
add
intto it and the add the extension to it which you can get by