Copy a file into the program's executable directory in C#

Sometimes it's handy to copy a file into the program's executable directory. For example, it's sometimes nice to copy a configuration file, database file, or other data file into the same directory as the executable. (It's handy for example programs such as the ones on this site, too.)

To copy a file into the executable directory, first add it to the project. To do that, open Solution Explorer, right-click the project (not the top-level solution), open the context menu's Add item, and select Existing Item. Browse to the file and select Add.

Next click on the file in Solution Explorer. In the Properties window, click on the Copy to Output Directory property and select one of the options:

  • Do not copy - Don't copy the file into the executable directory
  • Copy always - Copy the file into the executable directory every time Visual Studio builds the executable
  • Copy if newer - Copy the file into the executable directory if it is newer than the copy that is already in that directory (i.e. it has been modified).

Now the program can assume the file is in the same directory where it is executing. The following code shows how the example program displays an image file on its background assuming the file is in the program's startup directory.

// Load the picture from the startup directory.
private void Form1_Load(object sender, EventArgs e)
{
this.BackgroundImage = new Bitmap(".\\24hour_s.jpg");
this.ClientSize = this.BackgroundImage.Size;
}

  

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.