C# - Executing CMD.exe with Arguments containing %VS110COMNTOOLS% - winforms

I have been trying to execute the below mentioned command on cmd.exe from C#. I have tried the the below mentioned methods but none of them seem to work. They all are able to open CMD but nothing happens after that. Also if I use simple arguments like - "/C start winword" it works with Method 3 only.
Also I have tried adding /C and /K to the argumentstring but they don't seem to work as well.
string argumentString = "\"%VS110COMNTOOLS%/../IDE/devenv.exe\" /diff " + "\"" + txt_File1.Text + "\" \"" + txt_file2.Text + "\"";
//string argumentString = "start winword";
// Method 1
System.Diagnostics.Process ExecuteCommand = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.UseShellExecute = true;
startInfo.Arguments = argumentString;
ExecuteCommand.StartInfo = startInfo;
ExecuteCommand.Start();
//Method 2
System.Diagnostics.Process.Start(#"cmd.exe", argumentString);
// Method 3
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", argumentString);
procStartInfo.RedirectStandardOutput = true;
procStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = false;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
string result = proc.StandardOutput.ReadToEnd();
Console.WriteLine(result);

Adding /k to arguments of cmd.exe does the work.
Check out the code:
using System;
namespace ProcessRun
{
class Program
{
static void Main(string[] args)
{
//var argumentString = "\"%VS120COMNTOOLS%/../IDE/devenv.exe\" /diff " + "\"" + txt_File1 + "\" \"" + txt_file2 + "\"";
string argumentString = "start winword";
// Method 1
Method1(argumentString);
//Method 2
Method2(argumentString);
// Method 3
Method3(argumentString);
}
private static void Method3(string argumentString)
{
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/k " + argumentString);
procStartInfo.RedirectStandardOutput = true;
procStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = false;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
string result = proc.StandardOutput.ReadToEnd();
Console.WriteLine(result);
}
private static void Method2(string argumentString)
{
System.Diagnostics.Process.Start(#"cmd.exe", "/k " + argumentString);
}
private static void Method1(string argumentString)
{
System.Diagnostics.Process ExecuteCommand = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
startInfo.FileName = "cmd.exe";
startInfo.UseShellExecute = true;
startInfo.Arguments = "/k " + argumentString;
ExecuteCommand.StartInfo = startInfo;
ExecuteCommand.Start();
}
}
}

Related

Can't update db using c# loop

Im trying to update rows in my table using loop, I get no error but nothing changed in my data...Thats my code.. What am I missing ?
private void updateZipInDB(List<ZipObj> zipCodeToUpdate)
{
var comm = "";
string DbConnString = ConfigurationManager.AppSettings["dbConnectionString"].ToString();
using (SqlConnection conn = new SqlConnection(DbConnString))
{
comm = "UPDATE Account SET address1_postalcode = #newVal WHERE AccountId = #accountID";
using (SqlCommand command = new SqlCommand(comm, conn))
{
conn.Open();
command.Parameters.AddWithValue("#newVal", "f");
command.Parameters.AddWithValue("#accountID", "f");
for (int i = 0; i < zipCodeToUpdate.Count; i++)
{
zipCodeToUpdate[i].NewVal + "' WHERE AccountId = '" + zipCodeToUpdate[i].AccountId + "'";
command.Parameters["#newVal"].Value = zipCodeToUpdate[i].NewVal;
command.Parameters["#accountID"].Value = zipCodeToUpdate[i].AccountId;
command.ExecuteNonQuery();
}
conn.Close();
}
}
}

the given path formate is not supported in C# windows application while uploading files to ftp

i want to upload files to ftp but i get an error
The given path's format is not supported.
i have mention my code below kindly help me.
the path giving error , what should i need to keep path like ?
the following is my path
this.path = #"ftp://ip address/Requests/";
public bool UploadDocsToFTP(string SourceFilePath, string FileName)
{
string ServerUri = "";
string FTPUserName = "";
string FTPPassword = "";
string ftpURI = "";
try
{
try
{
ServerUri = ConfigurationManager.AppSettings["LinuxFileServerUri"];
FTPUserName = ConfigurationManager.AppSettings["LinuxFtpUserName"];
FTPPassword = ConfigurationManager.AppSettings["LinuxFtpPassword"];
string[] splitfilename = SourceFilePath.Split('\\');
//String businesRegId = splitfilename[2];
//String userRegId = splitfilename[3];
//String folderType = splitfilename[3];
//ftpURI = "ftp://" + ServerUri + "//" + businesRegId + "//" + userRegId;
//if (!string.IsNullOrEmpty(folderType))
// ftpURI += "//" + folderType;
//ServerUri = "ftp://" + ServerUri + "//" + businesRegId + "//" + userRegId + "//";
//if (!string.IsNullOrEmpty(folderType))
// ServerUri += folderType + "//";
// SetMethodRequiresCWD();
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ip address/Requests" + FileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(FTPUserName, FTPPassword);
FileStream fs = File.OpenRead(SourceFilePath + FileName);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
Stream ftpstream = request.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
ftpstream.Close();
}
catch (WebException e)
{
String status = ((FtpWebResponse)e.Response).StatusDescription;
if (UploadDocsToFTP_DirNotExists(SourceFilePath, FileName))
{
return true;
}
return false;
}
}
catch (Exception ex)
{
ex.ToString();
return false;
}
return true;
}
A URL (which is what your path is) cannot contain spaces or other certain characters, so you have to encode it.
You can use System.Net.WebUtility for this.
// instead of this:
// FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ip address/Requests" + FileName);
// do this:
string path = System.Net.WebUtility.UrlEncode("ftp://ip address/Requests" + FileName);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(path);

How to encrypt a file using a existing encryption batch file in C# using Processstartinfo?

Can anyone help me how to encrypt a file using a existing encryption script batch file in c# using ProcessStartInfo class?
I am new to the Encryption of a file. I am passing a parameter path, path of text file that I need to encrypt.
This is path of my encryption script batch file
D:\CBMS-Keenan\core\Transmittals\Scripts\123gpg.bat|gpg||false
This is my existing code
public string PerformAction(string path)// Path input file name path(.txt)
{
//TransmittalBatch batch = new TransmittalBatch();
string _transmitfile=string.Empty;
string text1 = "";
string batchfilename=Path.GetFileName(path);
string renamedfile = "";
if((this._filename!=null)&& (this._filename.Length > 0))
{
renamedfile = this._filename;
}
else
{
if(this._replacesuffix)
{
renamedfile = batchfilename.Remove(batchfilename.LastIndexOf("."));
}
else
{
renamedfile = batchfilename;
}
if((this._suffix!=null)&&(this._suffix.Length>0))
{
renamedfile = renamedfile + "." + this._suffix.Replace(".", "");
}
}
if ((batchfilename != null) && (batchfilename.Length > 0))
{
ProcessStartInfo _info = new ProcessStartInfo(this._scriptfile, "\"" + batchfilename + "\"\"" + renamedfile + "\"");//this._scriptfile is encryprtion batch file //batchfilename is input batch file which we got from the path//renamed file is the filerenamed after the encryption
_info.CreateNoWindow = true;
_info.RedirectStandardOutput = true;
_info.RedirectStandardInput = true;
_info.RedirectStandardError = true;
_info.UseShellExecute = false;
Process _process = Process.Start(_info);
StreamReader _streamreader1 = _process.StandardOutput;
StreamReader _streamreader2 = _process.StandardError;
_process.WaitForExit(300000);
if(_process.HasExited)
{
text1 = _streamreader1.ReadToEnd();
text1 = text1 + "Errors:\r\n";
text1 = text1 + _streamreader2.ReadToEnd();
}
//batch.RuleActionResults["LatestWorkingFilename"] = text3;
_process.StandardInput.WriteLine(text1);
_transmitfile = renamedfile;
}
else
{
text1 = "No files to encrypt!";
}
//batch.RuleActionResults["Encryption Results"] = text1;
string _ecnryptedfile = text1;
//Console.WriteLine("Encrypted result:" + _ecnryptedfile);
return _transmitfile;
//return batch.RuleActionResults["EncryptionResults"].ToString();
}

Generate code with recursion

I'm having issue with creating product code in recursion.
What I want to do is:
I enter code 1000
-If code exist in database regenerateCode(string code)
-else insert into database
Code:
(...)
if(codeExist)
CodeTB.Text = regenerateCode(string toParse); //toParse = 1000
string regenerateCode(string toParse)
{
string helper = "";
int parseCode = int.Parse(toParse);
helper = new string('0', 4 - parseCode.ToString().Length);
helper += parseCode + 1;
using (SqlConnection conn = new SqlConnection(cString.c_String))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT Product.productID FROM Product " +
"WHERE Product.PLU = '" + helper + "' ", conn))
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
// if code still exist in database, regenerate it
regenerateCode(helper);
}
else
{
//else return code
return helper;
}
}
}
}
return helper;
}
Actually it works fine with example:
1000 (exist)
1001 (exist)
1002 (not exist, insert), but
when code = 1002, it goes into line with else {return helper;} and have no idea why going again to regenerateCode() method..
Any ideas?
It happens because you do nothing with the return value. You pass helper to the recursion, but do not place the return value anywhere. your method should look like this:
string regenerateCode(string toParse)
{
string helper = "";
int parseCode = int.Parse(toParse);
helper = new string('0', 4 - parseCode.ToString().Length);
helper += parseCode + 1;
using (SqlConnection conn = new SqlConnection(cString.c_String))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT Product.productID FROM Product " +
"WHERE Product.PLU = '" + helper + "' ", conn))
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
// Return the next code that doesn't exist
return rdr.HasRows ? regenerateCode(helper) : helper;
}
}
}
}
Also, remember that while string are reference types, they are immutable. which means that a string that is passed as an argument would not change like a normal array. see: How are strings passed in .NET?

How to get alert when a message in delivered in window form application?

private void buttonSend_Click(object sender, EventArgs e)
{
InsertChatDetails();
//textBoxChat.Text += System.DateTime.Now.ToLongTimeString() + "" + System.Environment.GetEnvironmentVariable("Computername") + Environment.NewLine;
textBoxChat.Text += textBoxMessage.Text + Environment.NewLine;
textBoxMessage.Text = "";
}
public void InsertChatDetails() //Inserting Values
{
try
{
CommonCS CommonSample1 = new CommonCS();
BusinessCS BFSample1 = new BusinessCS();
CommonSample1.Id = "1";
CommonSample1.FromUser = textBoxChat.Text += System.DateTime.Now.ToLongTimeString() + "-->" + Program.UserName + Environment.NewLine;
//CommonSample1.FromUser = textBoxChat.Text += System.DateTime.Now.ToLongTimeString() + "" + System.Environment.GetEnvironmentVariable("Computername") + Environment.NewLine;
CommonSample1.ToUser = "";
CommonSample1.MessageText = textBoxMessage.Text;
CommonSample1.SentOn = DateTime.Now;
CommonSample1.StatusReport = 0;
BFSample1.InsertChatDetails(CommonSample1);
}
catch (Exception)
{
}
}
Not sure from your code what you are trying to do, but if its synchronous you can trace it after SendMessageToWinMachine() ,else you can use CallBack Method for asynchronus call.

Resources