Click here to Skip to main content
12,755,986 members (36,977 online)
Rate this:
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 7: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 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 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.
Matt T Heffron 8-Nov-12 17:20pm
Add System.Diagnostics.Debug.Assert(!File.Exists(dpath)); right before the File.Copy and see what happens...
Ankur\m/ 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?
Ankur\m/ 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.
Marcus Kramer 9-Nov-12 9:58am
Not from me.
Matt T Heffron 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
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web01 | 2.8.170217.1 | Last Updated 8 Nov 2012
Copyright © CodeProject, 1999-2017
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