Click here to Skip to main content
11,796,774 members (74,963 online)
Rate this: bad
Please Sign up or sign in to vote.
See more: C#
i am trying to copy a file from one place to another here is the code.
private void button1_Click(object sender, EventArgs e)
    OpenFileDialog openFileDialog2 = new OpenFileDialog();
    openFileDialog2.InitialDirectory = @"C:\";
    openFileDialog2.Title = "Browse Text Files";
    openFileDialog2.CheckFileExists = true;
    openFileDialog2.CheckPathExists = true;
if (openFileDialog2.ShowDialog() == DialogResult.OK)
       textBox2.Text = openFileDialog2.FileName;
string filename,filex;
   filex = openFileDialog2.SafeFileName;
   filename = textBox2.Text;
   string dpath = @"D:\G\"+ filex ;
   File.Copy(filename, dpath );
but it gives me the follwoing error
The file 'D:\G\openFileDialog2' already exists.
please tell me whats wrong with the code.
Posted 8-Nov-12 6:09am

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

The message is in a very simple English - the file at that location already exist. If you want to overwrite the file, use the overloaded method File.Copy Method (String, String, Boolean)[^]. Pass true to the overwrite parameter and it should be good.
saifullahiit at 8-Nov-12 13:05pm
no it does not exist on the destination. i have used the true parameter. i does not give the error but it does not copy the file either.
Marcus Kramer at 8-Nov-12 13:53pm
I would venture to guess that the file does exist at the location specified. If you think it doesn't, make sure that the file isn't hidden. If it is hidden, you may not see it in explorer, but it still exists.
Ankur\m/ at 9-Nov-12 0:23am
Yeah, even my first guess will be that the file is hidden.
Btw may I know why a 1-vote if it's by you?
Marcus Kramer at 9-Nov-12 9:58am
Not from me.
Matt T Heffron at 8-Nov-12 17:20pm
Add System.Diagnostics.Debug.Assert(!File.Exists(dpath)); right before the File.Copy and see what happens...
Ankur\m/ at 9-Nov-12 0:28am
I would guess it would return false. The system do a check for file existence before copying it. And that is what is giving an exception message here.
Matt T Heffron at 9-Nov-12 13:15pm
Ahhh... but you "would guess it would return false".

This would be definite. The OS's authoratative "statement" on if the file exists or not. (E.g. as others mentioned, hidden, etc.)

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

  Print Answers RSS
0 Abhinav S 369
1 OriginalGriff 360
2 Maciej Los 360
3 KrunalRohit 304
4 CPallini 295
0 OriginalGriff 2,032
1 Maciej Los 1,725
2 KrunalRohit 1,310
3 CPallini 1,055
4 ppolymorphe 883

Advertise | Privacy | Mobile
Web02 | 2.8.151002.1 | Last Updated 8 Nov 2012
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100