Reputation: 11191
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?
Upvotes: 0
Views: 212
Reputation: 6993
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
Upvotes: 2
Reputation: 88475
You can do all the directory stuff directly in C#, if that would be easier:
if (!Directory.Exists(@"c:\app\code")
{
Directory.CreateDirectory(@"c:\app\code");
}
else
{
Console.WriteLine("Directory already exists!");
}
See this page for more info: http://msdn.microsoft.com/en-us/library/wa70yfe2%28v=VS.100%29.aspx
Upvotes: 2
Reputation: 44327
Simplest answer is probably what you've already thought of - to create the directory from the application as it runs.
DirectoryInfo.Create() is the method you'll need.
Upvotes: 1