Click here to Skip to main content
15,885,985 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more: , +
Hello Guys, How are you, I hope you will be fine well I have another issue in my project last night I have code from Google to save image in directory folder with picture box but when I add the same pic in this folder soi get an error filename already exist I wanna overwrite image if image is also in folder so please guide me how can I do this


Thanks

What I have tried:

private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog opFile = new OpenFileDialog();
opFile.Title = "Select a Image";
opFile.Filter = "jpg files (*.jpg)|*.jpg|All files (*.*)|*.*";
string appPath = Path.GetDirectoryName(Application.ExecutablePath) + @"\CatImage\";
if (Directory.Exists(appPath) == false)
{
Directory.CreateDirectory(appPath);
}
if (opFile.ShowDialog() == DialogResult.OK)
{
//try
//{
string iName = opFile.SafeFileName; // <---
string filepath = opFile.FileName;
//dbpath = appPath+ @"\" + iName;
//dbpath = dbpath.Replace(@"\\", @"\");
dbpath = iName;
MessageBox.Show(dbpath);
// MessageBox.Show(dbpath);
File.Copy(filepath, appPath + iName);
pictureBox1.Image = new Bitmap(opFile.OpenFile());
//}
//catch (Exception exp)
//{
// MessageBox.Show("Unable to open file " + exp.Message);
//}
}
else
{
opFile.Dispose();
}
}
Posted
Updated 19-Jun-17 8:18am

1 solution

Call the overload of Copy which has an "overwrite" flag, and pass true:
Copy Method | Microsoft Docs[^]
C#
File.Copy(filepath, appPath + iName, true);
 
Share this answer
 
Comments
Member 9983063 19-Jun-17 14:40pm    
Thank you bro it's working thank you so much :)

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