I know that this is question was already asked but i couldn't find any answer . I have this code i'm trying to run an app with a specific user but gives error that file could not be found even if the file is there.
static void Main(string[] args)
{
System.Diagnostics.ProcessStartInfo myProcess = new System.Diagnostics.ProcessStartInfo("cinegy.exe");
myProcess.WorkingDirectory =Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)+ "\\Cinegy\\Cinegy Workflow 8.5.8\\";
System.Security.SecureString password = new System.Security.SecureString();
string uspw = "mypass";
foreach (char c in uspw)
{
password.AppendChar(c);
}
myProcess.UserName = "myuser";
myProcess.Password = password;
myProcess.Domain = "mydomain";
myProcess.UseShellExecute = false;
try
{
System.Diagnostics.Process.Start(myProcess);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
}
Thanks
Error is |The system cannot find the file specified|
If you use
UseShellExecute = false
it ignores WorkingDirectory
You can either set UseShellExecute to true and have a cmd shell. Or you add the location of the process to path of the process you are running:
string path = System.Environment.GetEnvironmentVariable("path");
path += ";" + Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + "\\Cinegy\\Cinegy Workflow 8.5.8\\";
System.Environment.SetEnvironmentVariable("path", path);
Related
This question already has an answer here:
How to run console application which is send pdf to printer in server?
(1 answer)
Closed 2 years ago.
I download .zip file from outlook then send pdf files to printer. It works on my local machine while compiling, However I setup published app on server, it downloads .zip file from outlook and open it but it can not send to printer . How can I handle that?
This is my code:
static void Main(string[] args)
{
ExchangeService exchange = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
exchange.Credentials = new WebCredentials("mail#", "password");
exchange.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
if (exchange != null)
{
SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
FindItemsResults<Item> result = exchange.FindItems(WellKnownFolderName.Inbox, sf, new ItemView(1));
foreach (Item item in result)
{
EmailMessage message = EmailMessage.Bind(exchange, item.Id);
message.IsRead = true;
message.Update(ConflictResolutionMode.AutoResolve);
List<Attachment> zipList = message.Attachments.AsEnumerable().Where(x => x.Name.Contains(".zip")).ToList();
foreach (Attachment Attachment in zipList)
{
if (Attachment is FileAttachment)
{
FileAttachment f = Attachment as FileAttachment;
f.Load("C:\\TEST\\" + f.Name);
string zipPath = #"C:\TEST\" + f.Name;
string extractPath = #"C:\TEST\" + Path.GetRandomFileName();
ZipFile.ExtractToDirectory(zipPath, extractPath);
string[] filePaths = Directory.GetFiles(extractPath, "*.pdf",
SearchOption.TopDirectoryOnly);
foreach (string path in filePaths)
{
SendToPrinter(path);
}
}
}
}
}
}
static void SendToPrinter(string path)
{
try
{
var printerName = "EPSON L310 Series";
ProcessStartInfo info = new ProcessStartInfo(path);
info.Verb = "PrintTo";
info.UseShellExecute = false;
info.CreateNoWindow = true;
info.WindowStyle = ProcessWindowStyle.Hidden;
info.Arguments = "\"" + printerName + "\"";
Process p = new Process();
p.StartInfo = info;
p.Start();
p.WaitForInputIdle();
System.Threading.Thread.Sleep(3000);
if (false == p.CloseMainWindow())
p.Kill();
}
catch (Exception ex)
{
Console.WriteLine("error:", ex.Message);
Console.ReadLine();
}
}
As I said, everything is work fine but printer not working. I can print pdf manually I mean machine works. Also this app works on my local machine
You need to change:
info.UseShellExecute = false;
to:
info.UseShellExecute = true;
since the path is a path to a PDF file, not an executable.
As per the docs:
When you use the operating system shell to start processes, you can
start any document (which is any registered file type associated with
an executable that has a default open action) and perform operations
on the file, such as printing, by using the Process object. When
UseShellExecute is false, you can start only executables by using the
Process object.
Additionally:
If you set the WindowStyle to ProcessWindowStyle.Hidden,
UseShellExecute must be set to true.
You are using Hidden - thus UseShellExecute must be true.
I am having a .rmd file [ R mark down file], it will do data validation for some specific scenario, i wanted to execute the rmd file from console application using c#, can some one help me doing the execution.
Finally I have done the above requirement as below,posting here since it can help some one on implementation
- created a R script and invoked Rmd script from the R script
- used command line code for invoking R script from C#.
R Script Sample:
rmarkdown::render(
input = rmdfilepath,
output_file = outputfilepath,
output_format = "all", output_options = list())
c# Sample:
private static string RunRScript(string rpath, string scriptpath, string inputfilepath,
string outputfilepath)
{
try
{
var info = new ProcessStartInfo
{
FileName = rpath,
WorkingDirectory = Path.GetDirectoryName(rpath),
Arguments = scriptpath + " " + inputfilepath + " " + outputfilepath,
RedirectStandardOutput = true,
CreateNoWindow = true,
UseShellExecute = false
};
using (var proc = new Process { StartInfo = info })
{
proc.Start();
return proc.StandardOutput.ReadToEnd();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return string.Empty;
}
I’m facing some issue w.r.t calling a .exe from MVC4.
I have a ActionResult method where I want to start a command prompt locally but it shouldnot run as IISPool Identity instead it should run as a user logged in, unlike we do RunAs manually.
I have to pass parameter to the command line and in turn receive the output. I have written a code but it is not returning anything. Can someone highlight where I made some mistake.
string _commandParameter = #"whoami";
try
{
var process = new Process
{
StartInfo =
{
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardInput = true,
RedirectStandardError = true,
Verb = "runas",
FileName = #"C:\Windows\System32\cmd.exe",
Domain = "dir",
UserName = userID,
Password = GetSecureString(userpassword),
Arguments = _commandParameter
}
};
process.Start();
string readToEndOutput = process.StandardOutput.ReadToEnd();
string readToEndError = process.StandardError.ReadToEnd();
process.WaitForExit();
}
catch (Exception ex)
{
log.Info("error as StackTrace Exception in Input ActionResult -" + ex.StackTrace.ToString());
log.Info("error as Message Exception in Input ActionResult -" + ex.Message.ToString());
}
public static SecureString GetSecureString(string str)
{
SecureString result = new SecureString();
try
{
if (string.IsNullOrWhiteSpace(str))
return null;
else
{
foreach (char c in str.ToCharArray())
result.AppendChar(c);
return result;
}
}
catch (Exception ex)
{
log.Info("Cannot create password-" + ex.StackTrace.ToString());
}
return result;
}
The output
I am trying to use c# to delete a user profile on a remote server. I am running the program as myself. If I browse to \\server\c$\Users\ as myself I can delete the directory "User". It gives no error. If I use my program written in C# with the code below to attempt to delete the same directory I get back this exception.
Access to the path 'appsFolder.itemdata-ms' is denied.
Am I doing something wrong with my delete?
Directory.Delete("\\\\server\\c$\\Users\\User\\",true);
Deleting a user profile folder without cleaning the registry accoringly can lead to several undesired side-effects like temporary profile creation etc.
i recommend using DeleteProfile function which can be found in userenv.dll
my code is as follow:
internal class Program
{
[DllImport("userenv.dll", CharSet = CharSet.Unicode, ExactSpelling = false, SetLastError = true)]
public static extern bool DeleteProfile(string sidString, string profilePath, string omputerName);
private static void Main(string[] args)
{
try
{
var username = args[0];
var principalContext = new PrincipalContext(ContextType.Domain); // Domain => to support local user this should be changed probably, didn't test yet
var userPrincipal = UserPrincipal.FindByIdentity(principalContext, username);
if (userPrincipal != null)
{
Console.WriteLine("User found");
var userSid = userPrincipal.Sid;
Console.WriteLine("User {0} has SID: {1}", username, userSid);
Console.WriteLine("Will try to DeleteProfile next..");
DeleteProfile(userSid.ToString(), null, null);
Console.WriteLine("Done - bye!");
}
else
{
Console.WriteLine("ERROR! User: {0} not found!", username);
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
}
}
consider, this code is just for demonstration purpose and should be stabilized for production..
cheers,
-Chris
btw, here more on MSDN
https://msdn.microsoft.com/en-us/library/windows/desktop/bb762273(v=vs.85).aspx
Hi I was trying to same thing and found Directory.Delete() cannot delete files if file is Hidden or a system file.
Using cmd instead to delete folder.
public static FileAttributes RemoveAttribute (FileAttributes att, FileAttributes attToRemove)
{
return att & ~attToRemove;
}
public void DeleteProfileFolder(string file)
{
Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WindowStyle = ProvessWindowsStyle.Hiddenl
startInfo.FileName = "cmd";
startInfo.Arguments = "/C rd /S /Q \"" + file + "\"";
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
}
public void Deletes(DirectoryInfo baseDir)
{
if(! baseDir.Exists)
return;
var Dirs = Directory.EnumerateDirectories(baseDir.ToString(),"*.*",SearchOption.TopDirectoryOnly);
var files = Directory.EnumerateFiles(baseDir.ToString(),"*.*",SearchOption.TopDirectoryOnly);
foreach(var dir in Dirs)
{
DeleteProfileFolder(dir);
}
foreach(var file in files)
{
FileAttributes att = File.GetAttributes(f);
if((att & FileAttributes.Hidden) == FileAttribute.Hidden)
{
att = RemoveAttribute(att, FileAttributes.Hidden);
File.SetAttributes(file , att);
File.SetAttributes(File, FileAttributes.Normal)
}
File.Delete(file);
}
}
To call This
Deletes("c:\Users\"); // did this on local system.
I havn't tried on network location but I thing this will work.
Note: To completely delete userProfile we also need to delete registry.
I have class in my WCF service to execute batch file. when I test to run the batch file in shared directory, everything is fine, the batch was executed, but when I try to run the batch file from secure diretory, I get error "ACCESS DENIED". How to add login property so I can access my secured directory to execute my batch file?
here is my code:
public string ExecuteBat()
{
string hasil = "";
ProcessStartInfo processInfo = new ProcessStartInfo(#"D:\Secure\command.bat");
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
Process process = Process.Start(processInfo);
process.WaitForExit();
if (process.ExitCode == 0)
{
hasil = "BAT EXECUTED!";
}
else
{
hasil = "EXECUTE BAT FAILED";
}
return hasil;
}
The ProcessStartInfo class has properties for Domain,UserName and Password that, when set, start the process under those credentials, something like this:
ProcessStartInfo processInfo = new ProcessStartInfo(#"D:\Rpts\SSIS_WeeklyFlash_AAF_1.bat");
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
processInfo.Domain= "MyCompanyDomain";
processInfo.UserName = "username";
//Secure string is an odd beast, so you need something like this:
SecureString ss = new SecureString();
string password = "p#$$w0rd";
foreach (char c in password)
{
ss.AppendChar(c);
}
processInfo.Password = ss;
...