Click here to Skip to main content
16,021,687 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All;
in my windows form app user can add image in a folder in hard drive with saveFileDialog.
How can I change the name of image instead of OverwritePrompt alert with adding a variable integer to the name of image?
I mean how can I automatically change the name (by adding a number) instead of the user tries to overwrite an existing file?
Posted

Hi Ali

Please first get the file name and path with FileName property from Save dialog and after check the file if the file is exist you should change the file name and save again ;)

C#
private void Save_Click(object sender, EventArgs e)
   {
       Random rnd = new Random(0);
       string filename = saveFileDialog1.FileName;
       if (System.IO.File.Exists(filename))
           filename += rnd.Next(1, 1000000);
   }


Best Regards.
 
Share this answer
 
Set the SaveFileDialog.OverwritePrompt property to false, and it will not display any further information to the user.
The dialog itself does not affect files at all: even if the file exists it will not be affected in any way by the dialog, only by your code.

So after the ShowDialog call, check if the file exists:
C#
SaveFileDialog sfd = new SaveFileDialog();
sfd.OverwritePrompt = false;
if (sfd.ShowDialog() == DialogResult.OK)
    {
    if (File.Exists(sfd.FileName))
        {
        // Change the name
        ...
        }
    }

You can then add the number yourself as needed.
(I would probably rename the existing file to "existingFileName.00001.originalextension" rather than adding a number to the newly saved file, but that's just me)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900