执行批处理文件时找不到文件

时间:2018-01-18 07:01:39

标签: c# batch-file environment-variables 7zip

我正在尝试执行批处理文件,该文件指示7zip压缩目录。当我通过“双击”文件运行它或者我尝试在命令提示符中运行它时,批处理文件正常工作。但是当我尝试通过C#应用程序执行文件时,我遇到了问题。下面是我在C#中的代码。

   string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
           path = path.Substring(0, path.IndexOf("Debug") + 6) + "Scripts";

            String EnvironmentPath = System.Environment
            .GetEnvironmentVariable("path", 
            EnvironmentVariableTarget.Machine);

            string[] varList = EnvironmentPath.Split(';');
            string enviVar=  varList.First(x=>x.Contains("7-Zip"));

            Process proc = new Process();

            proc = new Process();
            proc.StartInfo.WorkingDirectory = path;
            proc.StartInfo.Arguments = enviVar; 
            proc.StartInfo.FileName = "Script_To_BackUp_DB.bat";
            proc.StartInfo.CreateNoWindow = false;
            proc.StartInfo.UseShellExecute = false;
            proc.Start();

            proc.WaitForExit();

路径变量中的值为:D:\ Projects \ Common \ common \ Common \ Utilities \ Utilities \ bin \ Debug \ Scripts。 如果我删除“proc.StartInfo.UseShellExecute = false”行,那么批处理将执行并以异常结束,表示7z不被识别为内部或外部命令。我已经在环境变量中设置了路径。

批处理文件代码为:

 set backup_dir=C:\Users\FU386DKH\Desktop\Card logs\
 set db_dir=D:\Projects\Projects\db\

 :: set dt string in dd_mm_yy_HH_MM_SS format 
 set dt=%Date:~0,2%_%Date:~3,2%_%Date:~6,4%_%Date:~0,2%_%Date:~3,2%_%Date:~6,2%

 :: compress folder 
 7z a -tzip "%backup_dir%_%dt%.zip" "%db_dir%" -ssw

1 个答案:

答案 0 :(得分:0)

set backup_dir=C:\Users\FU386DKH\Desktop\ConsoleApplication2\
set db_dir=D:\Projects\NPCI\db\

:: set dt string in dd_mm_yy_HH_MM_SS format 
set dt=%Date:~0,2%_%Date:~3,2%_%Date:~6,4%_%Date:~0,2%_%Date:~3,2%_%Date:~6,2%

:: compress folder 
::Setting the path with the location of 7zip exe file. 
set PATH=%PATH%;C:\Program Files\7-Zip\
7z a -tzip "%backup_dir%_%dt%.zip" "%db_dir%" -ssw