%~dp0并从C#运行批处理文件

时间:2016-03-06 15:56:56

标签: c# batch-file

我在c:\ temp中有批处理,文件夹的hirachrcy看起来像

|
|- script.sql
|-executionbatch.bat

批次看起来像

@echo off

set scripts=_scripts.txt
set Instance=%1
set DataBase=%2
set Password=%3
set userName=%4

if "%1%" equ "" set instance="Ali"
if "%2%" equ "" set DataBase="Northwind"
if "%3%" equ "" set Password="123"
if "%4%" equ "" set userName="sa"

echo %Instance% 
echo %DataBase% 
echo %Password% 
echo %userName% 
rem
rem Make sure the scripts file exists.
rem
if not exist %scripts% (
    echo.
    echo Scripts file "%scripts%" does not exist.
    echo.
    goto error
)


rem
rem Clean output of any previous runs
rem
if exist %~dp0\__tmp* del /q %~dp0\__tmp*

rem
rem Apply all SQL scripts in order as listed in _scripts.txt
rem
rem NOTE: if any of the script filenames contain a space, this
rem for loop will only see the 1st component of the filename,
rem and then fail (file not found).  Do not use spaces in the
rem script filename.
rem
for /f "delims==" %%x in (%scripts%) do (
    echo.
    echo Applying script %%x...

    if not exist %CD%\%%x (
        echo.
        echo ERROR: script does not exist '%CD%\%%x'
        echo.
        goto error %%x
    )

    rem
    rem Make sure script exists
    rem
    if not exist "%~dp0\%%x" (
        echo.
        echo ERROR: script does not exist '%~dp0\%%x'
        echo.
        goto error
    )

    rem
    rem Run the script, show the output on stdout and tee this to a
    rem file with the same name as the script, prefixed with __tmp_
    rem

    sqlcmd -S%instance% -d%DataBase% -U%userName% -P%Password% -i"%~dp0\%%x" -o"%~dp0\__tmp_%%x.txt"
)


echo.
echo Done!
goto end

:error
echo.
endlocal
exit /b 1

:end
endlocal
exit /b 0

从C#运行时,它会搜索应用程序旁边的sql文件而不是批处理c#代码

    System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(string.Format(@"{0}Temp\\ExecutionBatch.bat", windowsPath));
    psi.RedirectStandardOutput = true;
    psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
    psi.UseShellExecute = false;
    System.Diagnostics.Process listFiles;
    listFiles = System.Diagnostics.Process.Start(psi);
    System.IO.StreamReader myOutput = listFiles.StandardOutput;
    listFiles.WaitForExit(2000);
    if (listFiles.HasExited)
    {
        string output = myOutput.ReadToEnd();

    }

0 个答案:

没有答案