Copy a directory hierarchy into the executable directory in C#


[executable directory]

The example Copy files into the executable directory in C# explains how to make Visual Studio copy a file into the executable directory when it builds a project. That makes it easy for the executable to find the file when it runs.

This example explains how to copy a whole directory hierarchy into the executable directory. For this example, suppose the directory is named Images and it is in the project directory. (Where the source code is.) To make Visual Studio copy it, follow these steps:

  1. Select the Project menu’s Properties command to open the project’s property pages.
  2. On the Build Events page, click Edit Post-build.
  3. In the “Post-build event command line” text box, enter the following code and click OK.
    xcopy "$(ProjectDir)\Images" "Images" /s /i /y



When you successfully build the program, Visual Studio copies the directory hierarchy from $(ProjectDir)\Images (the project directory) to the Images directory inside the executable directory.

When it starts, the program uses the following code to display an image file that was copied with the Images directory.

// Load the form's background image from
// a file in the Images directory.
private void Form1_Load(object sender, EventArgs e)
{
    this.BackgroundImage =
        new Bitmap(@"Images\CapeRoyal_NorthRim_GrandCanyon.jpg");
    this.ClientSize = this.BackgroundImage.Size;
}

(You might like to spend a few moments experimenting with post-build macros. Click the “Edit Post-build” button to display the Post-build Event Command Line editor. Use that dialog’s Macro button to see what macros are available.)


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in files, miscellany, system and tagged , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *