With platform dependent native libraries like SQLite we often need to get hold of the right DLL files for the given architecture and copy them to project’s output folder. But how to do it in an easy way? Pre-build event commands give us the answer.
First, you will want to create a folder for the library you want to copy and create subfolders for each architecture you need. In each of those folders just place all the DLLs and supporting files you need to copy.
Now right-click your Visual Studio project’s node in Solution Explorer, select Properties and then Build Events tab in the left pane. You will be presented with two empty boxes. In these boxes you can enter any commands that you want to execute before the project is built or after it is built, respectively.
Now, click the Edit Pre-build … button you are ready to enter your desired command. We can use the simple command line tool xcopy to copy the files from our library folder to the output directory:
xcopy $(ProjectDir)..\libs\sqlite\$(PlatformName)\* $(TargetDir) /E /Y
To explain what is going on here. The Xcopy tool has two main parameters – copy source and copy target. My sqlite folder is placed in a libs folder that is one level up from my project’s main directory (which is denoted by the “$(ProjectDir)” string) – hence I first navigate to parent folder by “..\” sequence and then to “libs\sqlite\” here I need to enter the correct subfolder for the current project architecture. We can get the “x64”, “x86”, or other current platform name using “$(PlatformName)” macro. Now finally in this folder I use an asterisk (“*”) to instruct xcopy to copy all files in the folder. The target directory for the build is specified by the “$(TargetDir)” macro and I also give two additional options “/E” (to include subfolders in the copying process) and “/Y” (to always overwrite existing files in the target directory).
Now along with each build action, our command will run and the files we need will be copied to the project’s target directory as we wanted. Simple enough, but saves a lot of manual labor.