I have a folder on the server containing pdf files(Windows Server 2008 R2 Enterprise). I have to open the folder with the authorized user account and display the pdf file in the browser. The user has full control permissions on the folder and is a member of the Administrator group.
Bellow code works from my local as it opens the pdf file from the folder located in the server in Adobe Reader. But on the server the process does not start(Adobe Reader does not open) and no exception occurs. Most of the forums say that turning off UAC will help, but I don't want to do it, because of security reasons.
How can I deal that issue? Please help.
try
{
WindowsIdentity wi = new WindowsIdentity(#"user_name#DOMAIN");
WindowsImpersonationContext ctx = null;
try
{
ctx = wi.Impersonate();
// Thread is now impersonating you can call the backend operations here...
Process p = new Process();
p.StartInfo = new ProcessStartInfo()
{
CreateNoWindow = true,
Verb = "open",
FileName = ConfigurationManager.AppSettings["mobil"] + "\\" + prmSicilNo + "_" + prmPeriod.ToString("yyyyMM") + ".pdf",
};
p.Start();
}
catch (Exception ex)
{
msj = ex.Message;
}
finally
{
ctx.Undo();
}
return msj;
}
catch (Exception ex)
{
return msj + "Error: " + ex.Message;
}
Try to execute your .exe with Run as Adminstrator on the server.If it works properly then add the below code:
p.StartInfo.Verb = "runas";
#Chintan Udeshi Thank you for you quick answer. I can run the AcroRd32.exe by Run as Administrator but when I tried with runas I got the error which says; "No application is associated with the specified file for this operation".
I also tried to place absolute Acrobat Reader Path, but it still didn't work. Any idea?
p.StartInfo = new ProcessStartInfo(#"C:\Program Files (x86)\Adobe\Reader 10.0\Reader\AcroRd32.exe")
{
CreateNoWindow = true,
Verb = "runas",
FileName = ConfigurationManager.AppSettings["mobil"] + "\\" + prmSicilNo + "_" + prmPeriod.ToString("yyyyMM") + ".pdf", // "c:\\pdf\\",
};
Related
I'm using Process to execute a batch file which will generate certificate file.
The code works great when I execute other file (which contains openssl command). But when I execute a file which contains keytool command, it executed, but no file was generated.
I've:
Set UseShellExecute true.
Set WaitForExit(-1) and find the return was true, so it did executed.
I clicked that batch file manually, and the file generates right away, so the command was fine :(
BTW I'm using .Net Core MVC.
I can't find any error code anywhere, so I'm at my wits' end now.
Does anyone has a clue? Any help would be very appriciated!
success code(openssl):
I generate a p12 file (a certificate format) in that folder first, and it works fine.
private string Gen_P12(string domain, string pwd)
{
//generate folder
string folder = #"D:\Temp\";
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
//generate bat(p12)
string bat = "openssl.exe pkcs12 -export -inkey " + domain + ".key -in " + domain + ".cer -out " + domain + ".p12 -password pass:" + pwd +"\r\n";
//download in folder
var path = Path.Combine(folder, domain + "_P12.bat");
using (FileStream fs = System.IO.File.Create(path))
{
byte[] content = new UTF8Encoding(true).GetBytes(bat);
fs.Write(content, 0, content.Length);
}
Thread.Sleep(500);
//execute
ProcessStartInfo myBat = new ProcessStartInfo();
string name = domain + "_P12.bat";
myBat.FileName = name;
myBat.WorkingDirectory = folder;
myBat.UseShellExecute = true;
//Process.Start(myBat);
Process p = Process.Start(myBat);
p.WaitForExit(-1);
return folder;
}
fail code(keytool):
Trying to use that P12 file and keytool command to generate a keystore (also a certificate format) but fail.
private string Gen_KS(string domain, string folder, string CA_domain, byte[] cer, string pwd)
{
//generate bat
string bat = "keytool -importkeystore -srckeystore " + domain + ".p12 -srcstoretype PKCS12 -srcstorepass " + pwd + " -destkeystore " + domain + ".keystore -storepass " + pwd + "\r\n";
var path = Path.Combine(folder, domain + "_KS.bat");
using (FileStream fs = System.IO.File.Create(path))
{
byte[] content = new UTF8Encoding(true).GetBytes(bat);
fs.Write(content, 0, content.Length);
}
Thread.Sleep(700);
//execute
ProcessStartInfo myBat = new ProcessStartInfo();
myBat.WorkingDirectory = folder;
string name = domain + "_KS.bat";
myBat.FileName = name;
myBat.UseShellExecute = true;
Process p = Process.Start(myBat);
var a = p.WaitForExit(-1);
string route = folder + domain + ".keystore";
return route;
}
Thanks!
Thanks to #user9938, I solved the problem!
1. Brief conclusion:
I need to process the bat as administrator.
(And I still don't get why only do the keytool command needs administrator rights)
2. Find the errors: (How to apply StanderError when UseShellExecute=true)
In fact we don't have to set it true to execute commands.
Try this (replace execute section):
Process process = new Process();
try
{
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.FileName = "cmd.exe";
process.Start();
process.StandardInput.WriteLine(bat); //command string, not the bat file
process.StandardInput.AutoFlush = true;
process.StandardInput.WriteLine("exit");
StreamReader reader = process.StandardError;
string curLine = reader.ReadLine();
reader.Close();
process.WaitForExit();
process.Close();
}catch (Exception e){}
Check the value of curLine through Breakpoints, the error message was: "'keytool' is not recognized as an internal or external command, operable program or batch file".
3. How to solve it:
Just set the Verb attribute as "runas".
//execute
ProcessStartInfo myBat = new ProcessStartInfo();
myBat.WorkingDirectory = folder;
string name = domain + "_KS.bat";
myBat.Verb = "runas";
myBat.FileName = name;
myBat.UseShellExecute = true;
Process p = Process.Start(myBat);
var a = p.WaitForExit(-1);
Done! Thank you user9938<3
I'm writing a program to launch a project.
Please tell me how to transfer parameters from such an ini file to exe?
[Data]
User = "Test"
UID = 1234
[Path]
Dir = E:\Test
Exe = test.exe
So I try to assign them
process.StartInfo.FileName = BasePath + "\\Loader.exe";
process.StartInfo.Arguments = Resources.Start;
process.StartInfo.WorkingDirectory = BasePath;
Please tell me how to implement this?
The ini file must be transferred, it does not accept a simple line. Or I am doing something wrong.
If I understand you well, this code should work
(replace "Loader.exe" and "inifile.ini" with proper names of your files):
ProcessStartInfo psi = new ProcessStartInfo(BasePath + "\\Loader.exe");
psi.Arguments = BasePath + "\\inifile.ini";
psi.WorkingDirectory = BasePath;
try
{
Process p = Process.Start(psi);
}
catch (Exception ex)
{
MessageBox.Show("Error:\n" + ex.InnerException, "Run Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
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 realize that in Windows 7, it is not possible to save different credentials for the same host, but I need some workaround.
Can I provide the username and password manually in the code? Store them in a temp .rdp file?
Process rdcProcess = new Process();
rdcProcess.StartInfo.FileName = Environment.ExpandEnvironmentVariables(#"%SystemRoot%\system32\cmdkey.exe");
rdcProcess.StartInfo.Arguments = "/generic:TERMSRV/192.168.0.217 /user:" + "username" + " /pass:" + "password";
rdcProcess.Start();
rdcProcess.StartInfo.FileName = Environment.ExpandEnvironmentVariables(#"%SystemRoot%\system32\mstsc.exe");
rdcProcess.StartInfo.Arguments = "/v " + "192.168.0.217"; // ip or name of computer to connect
rdcProcess.Start();
The above code initiates a connection with .217 and I am not being prompted to provide a password.
Thanks for help.
If you want to use powershell you could add the credentials using
cmdkey /generic:DOMAIN/"computername or IP" /user:"username" /pass:"password"
Then call RDP connection using
Start-Process -FilePath "$env:windir\system32\mstsc.exe" -ArgumentList "/v:computer name/IP" -Wait
If you want to delete the credentials run
cmdkey /delete:DOMAIN/"Computer name or IP"
Remember to remove ""
This is an updated version from Krzysiek's post.
var rdcProcess = new Process
{
StartInfo =
{
FileName = Environment.ExpandEnvironmentVariables(#"%SystemRoot%\system32\cmdkey.exe"),
Arguments = String.Format(#"/generic:TERMSRV/{0} /user:{1} /pass:{2}",
fp.ipAddress,
(String.IsNullOrEmpty(fp.accountDomain)) ? fp.accountUserName : fp.accountDomain + "\\" + fp.accountUserName,
fp.accountPassword),
WindowStyle = ProcessWindowStyle.Hidden
}
};
rdcProcess.Start();
rdcProcess.StartInfo.FileName = Environment.ExpandEnvironmentVariables(#"%SystemRoot%\system32\mstsc.exe");
rdcProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
rdcProcess.StartInfo.Arguments = String.Format("/f /v {0}", fp.ipAddress); // ip or name of computer to connect
rdcProcess.Start();
While trying to figure out how to allow users into our network, without giving them the keys to the castle, I enabled Remote Desktop Access for a few members of my team. Thinking more about this, I quickly remembered a project several years ago while working for the Department of Defense. That project required us to "lock down" access to only necessary personnel and limited access to the programs on the servers. After spending some time on Microsoft's KnowledgeBase, we realized that we could create desktop "shortcuts" for those employees that made the RDP connection, logged them in and limited their access to one specific application on that server.
#echo off
cmdkey /generic:TERMSRV/"*IP or Server Name*" /user:%username%
start mstsc /v:*IP or Server Name*
cmdkey /delete:TERMSRV/"*IP or Server Name*"
quit
The accepted answer solves the problem, but has the side effect of leaving the credentials in the users credential store. I wound up creating an IDisposable so I can use the credentials in a using statement.
using (new RDPCredentials(Host, UserPrincipalName, Password))
{
/*Do the RDP work here*/
}
internal class RDPCredentials : IDisposable
{
private string Host { get; }
public RDPCredentials(string Host, string UserName, string Password)
{
var cmdkey = new Process
{
StartInfo =
{
FileName = Environment.ExpandEnvironmentVariables(#"%SystemRoot%\system32\cmdkey.exe"),
Arguments = $#"/list",
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = false,
RedirectStandardOutput = true
}
};
cmdkey.Start();
cmdkey.WaitForExit();
if (!cmdkey.StandardOutput.ReadToEnd().Contains($#"TERMSRV/{Host}"))
{
this.Host = Host;
cmdkey = new Process
{
StartInfo =
{
FileName = Environment.ExpandEnvironmentVariables(#"%SystemRoot%\system32\cmdkey.exe"),
Arguments = $#"/generic:TERMSRV/{Host} /user:{UserName} /pass:{Password}",
WindowStyle = ProcessWindowStyle.Hidden
}
};
cmdkey.Start();
}
}
public void Dispose()
{
if (Host != null)
{
var cmdkey = new Process
{
StartInfo =
{
FileName = Environment.ExpandEnvironmentVariables(#"%SystemRoot%\system32\cmdkey.exe"),
Arguments = $#"/delete:TERMSRV/{Host}",
WindowStyle = ProcessWindowStyle.Hidden
}
};
cmdkey.Start();
}
}
}
most of the answers are incorrect, it still request password and this because execute different processes on the same process instance.
using command line works perfectly:
string command = "/c cmdkey.exe /generic:" + ip
+ " /user:" + user + " /pass:" + password + " & mstsc.exe /v " + ip;
ProcessStartInfo info = new ProcessStartInfo("cmd.exe", command);
info.WindowStyle = ProcessWindowStyle.Hidden;
info.CreateNoWindow = true;
Process proc = new Process();
proc.StartInfo = info;
proc.Start();
In debug mode, while running the C# WinForms App, I successfully select multiple files through the OpenFileDialog, which is then displayed in the logging window, these files are copied to a temp directory and I believe I get the error when trying to convert the excel files to csv. I get the following runtime debug error:
Error: You may not have permission to read the file or it may be corrupt.
Reported Error: Length Can not be less than zero.
Parameter Name: Length.
How do I fix this error?
Here's my code on MainForm.cs
// Consolidate Button Click Commands that executes if there are no user input errors
void ExecuteConsolidate()
{
string consolidatedFolder = targetFolderBrowserDialog.SelectedPath;
string tempfolder = targetFolderBrowserDialog.SelectedPath + "\\tempDirectory";
string sFile = "";
//create a temporary directory to store selected excel and csv files
if (!Directory.Exists(tempfolder))
{
Directory.CreateDirectory(tempfolder);
}
try
{
for (int i = 0; i < listBoxSourceFiles.Items.Count; i++)
{
sFile = listBoxSourceFiles.Items[i].ToString();
// Copy each selected xlsx files into the specified Temporary Folder
System.IO.File.Copy(textBoxSourceDir.Text + "\\" + sFile, tempfolder + #"\" + System.IO.Path.GetFileName(sFile), true);
Log("File " + sFile + " has been copied to " + tempfolder + #"\" + System.IO.Path.GetFileName(sFile));
} // ends foreach
Process convertFilesProcess = new Process();
// remove xlsx extension from filename so that we can add the .csv extension
string csvFileName = sourceFileOpenFileDialog.FileName.Substring(0, sourceFileOpenFileDialog.FileName.Length - 3);
// command prompt execution for converting xlsx files to csv
convertFilesProcess.StartInfo.WorkingDirectory = "I:\\CommissisionReconciliation\\App\\ConvertExcel\\";
convertFilesProcess.StartInfo.FileName = "ConvertExcelTo.exe";
convertFilesProcess.StartInfo.Arguments = " ^ " + targetFolderBrowserDialog.SelectedPath + "^" + csvFileName + ".csv";
convertFilesProcess.StartInfo.UseShellExecute = true;
convertFilesProcess.StartInfo.CreateNoWindow = true;
convertFilesProcess.StartInfo.RedirectStandardOutput = true;
convertFilesProcess.StartInfo.RedirectStandardError = true;
convertFilesProcess.Start();
//Process that creates all the xlsx files in temp folder to csv files.
Process consolidateFilesProcess = new Process();
// command prompt execution for CSV File Consolidation
consolidateFilesProcess.StartInfo.WorkingDirectory = targetFolderBrowserDialog.SelectedPath;
consolidateFilesProcess.StartInfo.Arguments = "Copy *.csv ^" + csvFileName + ".csv";
consolidateFilesProcess.StartInfo.UseShellExecute = false;
consolidateFilesProcess.StartInfo.CreateNoWindow = true;
consolidateFilesProcess.StartInfo.RedirectStandardOutput = true;
consolidateFilesProcess.StartInfo.RedirectStandardError = true;
consolidateFilesProcess.Start();
Log("All Files at " + tempfolder + " has been converted to a csv file");
Thread.Sleep(2000);
StreamReader sOut = consolidateFilesProcess.StandardOutput;
sOut.Close();
}
catch (SecurityException ex)
{
// The user lacks appropriate permissions to read files, discover paths, etc.
MessageBox.Show("Security error. The user lacks appropriate permissions to read files, discover paths, etc. Please contact your administrator for details.\n\n" +
"Error message: " + ex.Message + "\n\n");
}
catch (Exception ex)
{
// Could not load the image - probably related to Windows file system permissions.
MessageBox.Show("You may not have permission to read the file, or " +
"it may be corrupt.\n\nReported error: " + ex.Message);
}
try
{
if (Directory.Exists(tempfolder))
{
Directory.Delete(tempfolder, true);
}
}
catch (SecurityException ex)
{
// The user lacks appropriate permissions to read files, discover paths, etc.
MessageBox.Show("Security error. The user lacks appropriate permissions to read files, discover paths, etc. Please contact your administrator for details.\n\n" +
"Error message: " + ex.Message + "\n\n");
}
catch (Exception ex)
{
// Could not load the image - probably related to Windows file system permissions.
MessageBox.Show("You may not have permission to read the file, or " +
"it may be corrupt.\n\nReported error: " + ex.Message);
}
finally
{
// reset events
m_EventStopThread.Reset();
m_EventThreadStopped.Reset();
// create worker thread instance;
m_WorkerThread = new Thread(new ThreadStart(this.WorkerThreadFunction));
m_WorkerThread.Start();
}
} // ends void ExecuteConsolidate()
Thanks for looking! :)
All helpful answers will receive up-votes! :)
If you need more information like the workerThread method or the app.config code, let me know!
It is most likely this line that is causing your problem:
string csvFileName = sourceFileOpenFileDialog.FileName.Substring(0, sourceFileOpenFileDialog.FileName.Length - 3);
Why not use Path.GetFileNameWithoutExtension to get the filename without extension?
I suppose it dies here:
string csvFileName = sourceFileOpenFileDialog.FileName.Substring(0,
sourceFileOpenFileDialog.FileName.Length - 3);
Write it like this and see if it helps:
string selectedFile = sourceFileOpenFileDialog.FileName;
string csvFileName = Path.Combine(Path.GetDirectoryName(selectedFile),
Path.GetFileNameWithoutExtension(selectedFile));
This is the translation of your line.
But I think, you really wanted to just have the filename without path:
string csvFileName =
Path.GetFileNameWithoutExtension(sourceFileOpenFileDialog.FileName);
And to break on All Errors:
Go to "Debug" -> Exceptions (or CTRL+ALT+E)
Tick "Thrown" on Common Language Runtime Exceptions
Once done with you fix, dont forget to reset it (Reset All button)