Home > Mobile >  Calling cmd process doesn't appear to accept path in argument
Calling cmd process doesn't appear to accept path in argument

Time:06-19

I have a an application that runs daily and creates a log file; after a period of X days, the log files should be removed which I'm running at the end of all of the other code elements. Originally, this was being completed via PowerShell script however the client cannot run PowerShell code due to ExecutionPolicy on the machine that this application will be running. So, I'm attempting to convert to cmd process. Current code for log removal:

string arg2 = ConfigFile.OutputPaths.Log; //configuration value for log path
int arg2 = ConfigFile.DeleteLogsAfter; //configuration value for days

var processStartInfo = new ProcessStartInfo()
{
  FileName = @"cmd.exe",
  UseShellExecute = false,
  Arguments = $"FORFILES /P \"{arg1}\" /S /M *.* /D -{arg2} /C \"cmd /c del @path\""
};

Process process = Process.Start(processStartInfo);
process.WaitForExit(1000);

This produces the following error:

Could Not Find C:\code\exe_name\debug\@path

In debug, when I view the argument, which is:

FORFILES /P "C:\Work\Clients\Test Files\Logs" /S /M *.* /D -13 /C "cmd /c del @path"

that is being created, if I copy and paste into a command prompt window, it will execute and perform the deletion as expected.

Any ideas how why it isn't accepting the path argument in the process as it does in cmd?

CodePudding user response:

From forfiles help: There are some disadvantages to using CMD.exe with FORFILES, a new process will be created and destroyed for every file that FORFILES processes, so if you loop through 1000 files, then 1000 copies of CMD.exe will be opened and closed, this will affect performance. Also any variable created with SET will be lost as soon as FORFILES moves on to the next file.

In most cases using a simple FOR command along with Parameter extensions will provide a better/less buggy solution.

Could you do someting like that:

using System. IO;

string[] files = Directory. GetFiles(dirName);
​
foreach (string file in files)
{
FileInfo fi = new FileInfo(file);
if (fi. LastAccessTime < DateTime. Now. AddDays(-10)) ...
  • Related