Search code examples
c#wpfbatch-fileechomkdir

Batch scripting for directories or better method


Looking at creating a simple batch file for my app. My app needs some directories to be in place as it runs.

The first method I thought was just make a batch script:

@ECHO OFF
IF NOT EXIST C:\App GOTO :CREATE ELSE GOTO :DONTCREATE

:CREATE
MKDIR C:\App\Code
ECHO DIRECTORY CREATED

:DONTCREATE
ECHO IT WAS ALREADY THERE

1) This doesn't run as I would expect. Both :CREATE and :DONTCREATE seem to run regardless? How do I do an If properly then?

Output:

A subdirectory or file C:\App\Code already exists.
DIRECTORY CREATED
IT WAS ALREADY THERE

So it enters both true and false statements?

2) The app is a C# WPF app. For what I am trying to do here (create a couple of directories if they don't already exist) - should I do it some other way? Perhaps in the application as it runs?

edit: Ok, happy to just do in C# code - but can anyone explain the problem with my batch?


Solution

  • the problem is perhaps that you think of the GOTO targets as method start points. They are just labels in the file. This means that after

    IF NOT EXIST C:\App GOTO :CREATE ELSE GOTO :DONTCREATE
    

    execution picks up with

    :CREATE
    

    and then continues on down the script right through

    :DONTCREATE
    

    until the end of the file is reached. You have to add another GOTO if you want to go somewhere else after :CREATE finishes. The usual case is to tell it to GOTO :EOF (a built-in label) at the end, as follows:

    @ECHO OFF
    IF EXIST C:\App GOTO :DONTCREATE
    
    :CREATE
    MKDIR C:\App\Code
    ECHO DIRECTORY CREATED
    GOTO :EOF
    
    :DONTCREATE
    ECHO IT WAS ALREADY THERE