I need to run this as an administrator
string cname = Environment.UserDomainName + "\\" + Environment.UserName;
string resetTrust = "netdom /resetpwd /s:server01 /ud:" + cname + "/pd:" + textBoxPassword.Text.Trim();
String output = ExecuteCommandAsAdmin(resetTrust);
MessageBox.Show(output);
Here is the method ExecuteCommandAsAdmin
public static string ExecuteCommandAsAdmin(string command)
{
string cname = Environment.UserDomainName + "\\" + Environment.UserName;
ProcessStartInfo procStartInfo = new ProcessStartInfo()
{
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true,
FileName = "runas.exe",
Arguments = "/user:" + cname + "\"cmd /K " + command + "\""
};
using (Process proc = new Process())
{
proc.StartInfo = procStartInfo;
proc.Start();
string output = proc.StandardOutput.ReadToEnd();
if (string.IsNullOrEmpty(output))
output = proc.StandardError.ReadToEnd();
return output;
}
}
If you know a better way to do this, please let me know. I am not storing the password. Just passing it so it can be executed. If the wrong person enters the wrong password, nothing happens since they aren't an Admin.
Thank You
Use runas /user:name#domain cmd
Related
I'm having an issue where my cmd windows is just blank when executed from code. I've searched here and there for some solutions. And tried a few different things myself.
Running it with a normal .bat file works just fine.. But just not from my C# application.
Note: the ffmpeg is being run perfectly, but just not showing anything in the cmd window when executed from code.
image at the bottom.
I'll update this if I find a solution.. Unless you guys do it first ;)
Code:
private async void RunFfmpeg()
{
await Task.Run(() =>
{
String destFolder = null;
String sourceFolder = null;
int listCount = 0;
this.Dispatcher.Invoke(() =>
{
destFolder = textDest.Text;
sourceFolder = textSource.Text;
listCount = listFiles.Items.Count;
});
foreach (FileInfo fileC in listFiles.Items)
{
//Changing old extension to mp4
string oldFileName = fileC.ToString();
string newFileName = null;
string[] extension = oldFileName.Split('.');
newFileName = extension[0] + ".mp4";
string newDir = destFolder + "\\" + extension[0];
DirectoryInfo createDir = new DirectoryInfo(newDir);
if (!createDir.Exists)
{
createDir.Create();
}
//Gathering folders and all I need...
string output = "\"" + destFolder + "\\" + extension[0] + "\\" + newFileName + "\"";
string input = "\"" + sourceFolder + "\\" + oldFileName + "\"";
var startInfo = new System.Diagnostics.ProcessStartInfo
{
FileName = "cmd.exe",
//Arguments = $"-i {input} {output}",
Arguments = $"/c ffmpeg -i {input}" + " -c:a copy -c:v copy " + $"{output}",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = false,
WorkingDirectory = Directory.GetCurrentDirectory()
};
Process p = new Process();
p.StartInfo = startInfo;
p.OutputDataReceived += P_OutputDataReceived;
p.Start();
p.WaitForExit();
}
});
}
Here is where I read the output:
private void P_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
this.Dispatcher.Invoke(() =>
{
//string cmdBox = cmdOutput.Text;
//cmdOutput.AppendText(cmdBox);
//cmdOutput.Clear();
cmdOutput.AppendText(e.Data);
});
}
I've been trying all day to start process which would run the following code:
C:\bin\ant.bat -f=C:\build.xml -DinputFile=C:\Desktop\Book1.xml -DstartDate=2018-06-20 -DxslFile=ProcessingDate -DoutputFile=fff
and it works completely fine in cmd.
this is my last code in C# which I really hoped would work, but however it doesn't:
public void run() {
string antFile = #"C:\ant.bat";
string build = #"C:\build.xml";
string inputFile = #"C:\Book1.xml";
string startDate = "2018-05-23";
string outputFile = "ff";
ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd.exe", "/c" + #"C:bin\ant.bat -f=C:\build.xml -DinputFile=C:\Desktop\Book1.xml -DstartDate=2018-06-20 -DxslFile=ProcessingDate -DoutputFile=test0.xsl");
Process proc = new Process();
proc.StartInfo = procStartInfo;
proc.Start();
ProcessStartInfo procStartInfo2 = new ProcessStartInfo("cmd.exe", "/c" + antFile + "-f=" + build + "-DinputFile=" + inputFile + "-DstartDate=" + startDate + "-DxslFile=" + startDate + "-DoutputFile=" + outputFile);
Process proc2 = new Process();
proc2.StartInfo = procStartInfo2;
proc2.Start();
}
Firstly, I've tried to just put everything from cmd to the process but it didn't work, after I tried to do what I actually have to: put all the string values as arguments but it didn't work either.
Instead I am getting bunch of exceptions
I'm literally out of options as I've sat all day doing this. Does anyone have idea what problem it could be?
UPDATE:
I've managed to run startInfo3 process. But startInfo4 still doesn't work. I've checked both lines seem to produce the same so what's wrong with it if they're are the same. Do I pass them incorrectly?
ProcessStartInfo startInfo3 = new ProcessStartInfo();
startInfo3.FileName = "cmd.exe";
startInfo3.Arguments = "/c" + #"C:\ant.bat -f=C:\build.xml -DinputFile=C:\Book1.xml -DstartDate=2018-06-20 -DxslFile=ProcessingDate -DoutputFile=fff";
Process.Start(startInfo3);
ProcessStartInfo startInfo4 = new ProcessStartInfo();
startInfo4.FileName = "cmd.exe";
startInfo4.Arguments = "/c" + antFile + "-f=" + build + "-DinputFile=" + inputFile + "-DstartDate=" + startDate + "-DxslFile=" + startDate + "-DoutputFile=" + outputFile;
Process.Start(startInfo4);
After digging a bit more I figured out an answer:
ProcessStartInfo procStartInfo5 = new ProcessStartInfo();
procStartInfo5.FileName = "cmd.exe";
procStartInfo5.Arguments = $"/c{antFile} -f={build} -DinputFile={inputFile} -DstartDate={startDate} -DxslFile=ProcessingDate -DoutputFile={outputFile}";
Process.Start(procStartInfo5);
Hope it helps someone!
How to set a directory and execute a file conversion in Pandoc using C#.
string processName = "pandoc.exe";
string arguments = #"cd C/Users/a/Desktop/ConvertFileApp/ConvertFileApp/bin/Debug/marcdovd "
+ "chapter1.markdown "
+ "chapter2.markdown "
+ "chapter3.markdown "
+ "title.txt "
+ "-o progit.epub";
var psi = new ProcessStartInfo
{
FileName = processName,
Arguments = arguments,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardInput = true
};
var process = new Process { StartInfo = psi };
process.Start();
this code does not work.
You're calling the executable with the cd command as an argument. That's the equivalent of running the following on the command line:
pandoc.exe cd C/Users/a/Desktop/ConvertFileApp/ConvertFileApp/bin/Debug/marcdovd chapter1.markdown chapter2.markdown chapter3.markdown title.txt -o progit.epub
While I'm not familiar with Pandoc, I imagine you actually want to do something like this:
cd C:/Users/a/Desktop/ConvertFileApp/ConvertFileApp/bin/Debug/marcdovd
pandoc.exe chapter1.markdown chapter2.markdown chapter3.markdown title.txt -o progit.epub
To do this, remove the cd command from your arguments and set the ProcessStartInfo.WorkingDirectory property like so:
string processName = "pandoc.exe";
string arguments = "chapter1.markdown "
+ "chapter2.markdown "
+ "chapter3.markdown "
+ "title.txt "
+ "-o progit.epub";
var psi = new ProcessStartInfo
{
FileName = processName,
Arguments = arguments,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardInput = true,
WorkingDirectory = #"C:/Users/a/Desktop/ConvertFileApp/ConvertFileApp/bin/Debug/marcdovd"
};
var process = new Process { StartInfo = psi };
process.Start();
I am creating a Visual C# application that fills in the correct parameters in the command prompt to retrieve iTunes Sales and Trends data. My goal is to pass a string to the command prompt but I've only gotten as far is to locating the right directory. Below is the code I currently have.
string argument = (#"c/ java Autoingestion Credentials.properties " + lblVenderID.Text + " " + ddlReportType.Text + " " + ddlDateType.Text + " " + ddlReportSubtype.Text + " " + txtDate.Text);
System.Diagnostics.ProcessStartInfo process = new System.Diagnostics.ProcessStartInfo();
process.FileName = "cmd.exe";
process.WorkingDirectory = "C:/iTunes Sales Report/AutoIngestion";
System.Diagnostics.Debug.WriteLine(argument);
process.WindowStyle = System.Diagnostics.ProcessWindowStyle.Maximized;
System.Diagnostics.Process.Start(process);
As you can in the picture, it locates to the directory that I hard coded in, but it does not display the string of text that actually runs the command I want it to run.
If there is a way to display the text in the command line before pressing enter to run the command automatically that would be great. Any feedback would be appreciated.
If you are trying to run a cmd and write to it then this should do it:
var processInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
WorkingDirectory = "C:/iTunes Sales Report/AutoIngestion",
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = false
};
var process = new Process {StartInfo = processInfo };
process.Start();
// This will write your command and excute it
process.StandardInput.WriteLine(argument);
process.WaitForExit();
If you want to view the output, here is how:
string output = string.Empty;
string error = string.Empty;
//If you want to read the Output of that argument
using (StreamReader streamReader = process.StandardOutput)
{
output = streamReader.ReadToEnd();
}
//If you want to read the Error produced by the argument *if any*
using (StreamReader streamReader = process.StandardError)
{
error = streamReader.ReadToEnd();
}
I need to write a small utility to rebuild solution. I am using below code to do the same.
string solutionFile = #"E:\Projects\TFS\Code\WebSite.sln";
string cmd1 = #"""C:\Program Files\Microsoft Visual Studio 11.0\VC\vcvarsall.bat"" x86" + " &devenv " + "\"" + solutionFile + "\"" + " /rebuild release";
cmd1 = "\"" + cmd1 + "\"";
String command = String.Format("{0} {1}", #"/k ", cmd1);
ProcessStartInfo cmdsi = new ProcessStartInfo("cmd.exe")
{
UseShellExecute = false,
RedirectStandardOutput = true
};
cmdsi.Arguments = command;
using (Process cmd = Process.Start(cmdsi))
{
using (StreamReader reader = cmd.StandardOutput)
{
string result = reader.ReadToEnd();
listBox1.Items.Add(result);
}
}
If you will observe in command prompt then you can see executions output but same thing is not getting reflected in list box.
Please help to solve this issue.
Thank you in advance.
You can redirect the output to a temporary file and then can read the file like-
string cmd1 = "help > e:/temp.txt"; //e:/temp.txt is temporary file where the output is redirected.
String command = String.Format("{0} {1}", #"/k ", cmd1);
ProcessStartInfo cmdsi = new ProcessStartInfo("cmd.exe")
{
//You don't need to read console outputstream
//UseShellExecute = false,
//RedirectStandardOutput = true
};
cmdsi.Arguments = command;
using (Process cmd = Process.Start(cmdsi))
{
//Check if file exist or you can wait till the solution builds completely. you can apply your logic to wait here.
if (File.Exists("E:/temp.txt"))
{
//Read the files here
string[] lines = File.ReadAllLines("E:/temp.txt");
//Do your work here
}
}
You can do it async:
string solutionFile = #"E:\Projects\TFS\Code\WebSite.sln";
string batFile = #"C:\Program Files\Microsoft Visual Studio 11.0\VC\vcvarsall.bat";
string args = "x86" + " &devenv " + "\"" + solutionFile + "\"" + " /rebuild release";
ProcessStartInfo cmdsi = new ProcessStartInfo(batFile)
{
Arguments = args,
UseShellExecute = false,
RedirectStandardOutput = true
};
using (Process cmd = new Process())
{
cmd.StartInfo = cmdsi;
cmd.OutputDataReceived += (sender, args) => listBox1.Items.Add(string.IsNullOrEmpty(args.Data) ? string.Empty : args.Data);
cmd.Start();
}