问题
I run cmd.exe to move a file with Administrator rights:
ThisParams := '/C move ' + '"' + ThisSourceFile + '"' + ' ' + '"' + ATargetFile + '"';
Winapi.ShellAPI.ShellExecute(0, 'runas', 'cmd.exe', PChar(ThisParams), '', Winapi.Windows.SW_HIDE);
Unfortunately, ShellExecute
always gives back success, regardless of whether the move action was successful or not (the move action would fail for example if the target file exists and it is read-only or if the target disk is write-protected).
So how can I get notified if the move action in the above case fails?
回答1:
Perhaps you can use pipes and the load generated file ex. move A.txt B.TXT >result.txt
procedure TForm1.Button1Click(Sender: TObject);
var
stToDo: string;
sl1 : TSTringList ;
MyResult : boolean ;
begin
stToDo := '/C move "C:\Users\awr\Desktop\D2\a.txt" "C:\Users\awr\Desktop\D2\b.txt" >C:\Users\awr\Desktop\D2\Result.txt';
ShellExecute(Application.Handle, 'runas', 'cmd.exe' ,PChar(stToDo),'', SW_HIDE);
sl1 := TSTringList.create ;
sl1.LoadFromFile('C:\Users\awr\Desktop\D2\Result.txt');
MyResult := trim(sl1.text) <> '' ;
sl1.Free ;
If the move fail "result.txt" is empty
来源:https://stackoverflow.com/questions/59613168/get-notified-if-cmd-exe-fails-to-successfully-move-a-file