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 O开发者_JAVA技巧FF
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?
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
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
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.
精彩评论