How to copy a file to a directory in DOS, and create directories if necessary?

How can I copy a file using DOS commands into a directory structure that may not yet exist? I need to be able to force the creation of the directory path to the target file location if that location doesn't already exist.

For example, there is already a file.txt in this location:

C:\file.txt

And I want to copy it to

C:\example\new\path\to\copy\of\file\file.txt

but at this time

C:\example\

and all the subdirectories may or may not yet exist.

Basically, I am looking for a "copy and create the target path if necessary" command. What would you recommend is the best way to achieve this?


Yeah, that's xcopy. Here's what it'll look like:

xcopy file.txt c:\example\new\path\to\copy\of\file\file.txt

XCOPY info at

  • Commandlinefu xcopy
  • TechNet Xcopy Article
  • Wikipedia xcopy

You might also want to look into ROBOCOPY, in the XP resource kit and standard in Vista, Windows 7, and Server 2008.

robocopy . c:\example\new\path\to\copy\of\file file.txt

I tried using something like:

xcopy file.txt c:\example\new\path\to\copy\of\file\file.txt

But it would ask me if it was a file or directory. Since I had that in a batch file with 40000 files, it would be impractical. This solution only solves partially my problem: it creates the directory structure, but it requires user interaction. I found the solution to my problem here:

https://stackoverflow.com/questions/4283312/batch-file-asks-for-file-or-folder

Which is basically to add a "*" at the end of the destination file:

xcopy file.txt c:\example\new\path\to\copy\of\file\file.txt*

EDIT: as pointed by @romkyns, it may have undesired results if you have files that have the same name plus something else (like 'file.txt.bak'). In the same thread posted above, another solution that works is piping "echo f" to your command:

echo f | xcopy file.txt c:\example\new\path\to\copy\of\file\file.txt

Where you should substitute the "f" for whatever letter your system uses for file, in case you're using it in another language..