Solved

How do I access a command line argument from my application called through a .bat file?

Posted on 2014-01-15
25
437 Views
Last Modified: 2014-01-16
I'm writing a desktop application in VS 2012 C# and am wanting to know if there is another way to access a command line argument? Specifically, and maybe I'm missing some parts of this equation so i'm looking for some guidance, what I'd like to do, and what I thought I've seen done in the past is:

1.

Set a shortcut to my application on the desktop

2.

Right click on the icon, and set edit the properts (the target: property) to run a .bat file

3.

in that .bat file pass a command line argument to the application

4.

Inside my form_Load event, access that command line argument
This is not a console application. Is this even possible? Or would it just be easier to include a .txt file in the folder where the executable lives and have my application read that text file? If it is possible, what would the command inthe .bat file look like?
0
Comment
Question by:mikesExpertExchange
  • 14
  • 9
  • 2
25 Comments
 
LVL 39

Expert Comment

by:Kyle Abrahams
ID: 39783777
From:
http://www.howtogeek.com/howto/programming/get-command-line-arguments-in-a-windows-forms-application/

string[] args = Environment.GetCommandLineArgs();

Then you have an array that has your args.

Note there's no need for a bat file to do this, you can edit the shortcut directly to pass in the args, but either way the final output of the command line call would look something like:

"C:\program files\My Program Folder\MyProgram.Exe Param1 Param2 ParamN"

(or use x86 if you're building a 32 bit app in a 64 bit OS)
0
 
LVL 1

Author Comment

by:mikesExpertExchange
ID: 39783795
@Kyle: Thank you. I should've mentioned, the users won't be using a command line either, they will be double clicking on the icon. So, with that being said, can I alter the target path in the the properties dialog to something like what you have above? Or where exactly do I edit the shortcut to take in parameters properly? Right now when I add a value after the .exe in the target property, I get an error telling me I have an invalid directory path.
0
 
LVL 1

Author Comment

by:mikesExpertExchange
ID: 39783828
@Kyle: the image contains what my target property looks like and what I'm getting when I double click the icon.

Invalid Directory Error
0
 
LVL 39

Expert Comment

by:Kyle Abrahams
ID: 39783983
Can you confirm there's actually a c:\Dev\SendGL\bin\release folder?

Also it says the path sohuld end with  a \ . . . so change the Start In to be

c:\Dev\SendGL\bin\Release\

For the target I would make it:

"c:\Dev\SendGL\bin\release\SendGL.exe T" just to be on the safe side.

If you take out the "T" does it launch fine?
0
 
LVL 1

Author Comment

by:mikesExpertExchange
ID: 39784066
@Kyle: the path does exist, i did check. when I change the target to what you suggest I get:

double quote error
Yes, when I take the "T" out, it launches fine. Also, if I take the "T" out, but leave the path enclosed in quotes, when I click "apply", it automatically removes the quotes. Just thought I'd mention that for what ever its worth.
0
 
LVL 34

Expert Comment

by:Duncan Roe
ID: 39784297
You only need to enclose the path in quotes if it contains spaces, which your path doesn't.
You must have un-quoted space between path and command-line argument(s)
0
 
LVL 1

Author Comment

by:mikesExpertExchange
ID: 39784327
@Duncan: you mean as in my original picture above? is that the way it should look in the Target Field?
0
 
LVL 34

Expert Comment

by:Duncan Roe
ID: 39784431
Yes, it looks fine to me.
But, it didn't work for you. You could try "c:\Dev\SendGL\bin\release\SendGL.exe" "T" and see which quotes it removes when you click Apply.
Also, what happens when you click the Open File Location button?
0
 
LVL 1

Author Comment

by:mikesExpertExchange
ID: 39785594
@Duncan: When I put quotes around both, and click apply it removes the quotes from around the path, but leaves them around the parameter, but I get the same error when I try to run the application.

When I click on the Open File Location button it opens up to my release directory for the application (see included image).

open file location
0
 
LVL 39

Expert Comment

by:Kyle Abrahams
ID: 39785645
Just to isolate this can you try launching it from a command prompt:

Start -> run -> cmd
cd c:\dev\sendGL\bin\release

SendGL.exe T

Open in new window

and ensure that runs and you can read the param?
0
 
LVL 1

Author Comment

by:mikesExpertExchange
ID: 39785875
@Kyle: i got the following from running it through the command prompt:

command prompt execute
0
 
LVL 39

Expert Comment

by:Kyle Abrahams
ID: 39785891
Looks like that's coming from the program itself.

Search on "invalid directory" in your code.
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 1

Author Comment

by:mikesExpertExchange
ID: 39786020
@Kyle: I searched my code for that and nothing came up.
0
 
LVL 39

Expert Comment

by:Kyle Abrahams
ID: 39786176
can you post your code for your form load?
0
 
LVL 1

Author Comment

by:mikesExpertExchange
ID: 39786351
private void frmSend_Load(object sender, EventArgs e)
        {
           try
           {
                string[] args = Environment.GetCommandLineArgs();
                myGlobalVars.gbTEST_MODE = true;
                lblTestMode.Visible = true;
                myGlobalVars.gbSilentMode = false;
                myGlobalVars.gbIsReProc = false;
                myGlobalVars.gbIgnoreRefresh = true;
                try
                {
                    RegistryKey doesKeyExist = Registry.CurrentUser.OpenSubKey(@"Software\VB and VBA Program Settings\Send\General\", true);
                    if (doesKeyExist != null)
                    {
                        myGlobalVars.gsDirectory = Registry.GetValue(@"HKEY_CURRENT_USER\Software\VB and VBA Program Settings\Send\General", "DefaultDirectory", "").ToString();
                        this.Text = doesKeyExist.GetValue("DefaultDirectory").ToString();
                    }
                    else
                    {
                        RegistryKey newKey = Registry.CurrentUser.CreateSubKey(@"Software\VB and VBA Program Settings\Send\General");
                        newKey.SetValue("DefaultDirectory", @"\\blah\blah\blah");
                        myGlobalVars.gsDirectory = Registry.GetValue(@"HKEY_CURRENT_USER\Software\VB and VBA Program Settings\Send\General", "DefaultDirectory", "").ToString();
                        this.Text = myGlobalVars.gsDirectory.ToString();
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show("Building Registry Tree/Key ERROR: 'frmSend_Load' method: " + ex.Message.ToString());
                    writeToLogFile(ex.Message.ToString());
                }
                this.Text = "SENDGL Upload Utility (" + myGlobalVars.gsDirectory.ToString() + ")";

                RefreshFileList(true, false);
                myGlobalVars.gbIgnoreRefresh = false;
            }
            catch (Exception ex)
            {
writeToLogFile(ex.Message.ToString());
            }
        }

Open in new window

0
 
LVL 39

Expert Comment

by:Kyle Abrahams
ID: 39786373
Can you add the lines just for a test:

private void frmSend_Load(object sender, EventArgs e)
        {
            string[] args = Environment.GetCommandLineArgs();
 

// BEGIN INSERT
           foreach  (string arg in args)
               MessageBox.Show(arg, "args");
          
           return;
           // the rest will be unexecuted
        
// END INSERT


            myGlobalVars.gbTEST_MODE = true;
                lblTestMode.Visible = true;
                myGlobalVars.gbSilentMode = false;
                myGlobalVars.gbIsReProc = false;
                myGlobalVars.gbIgnoreRefresh = true;
                try
                {
                    RegistryKey doesKeyExist = Registry.CurrentUser.OpenSubKey(@"Software\VB and VBA Program Settings\Send\General\", true);
                    if (doesKeyExist != null)
                    {
                        myGlobalVars.gsDirectory = Registry.GetValue(@"HKEY_CURRENT_USER\Software\VB and VBA Program Settings\Send\General", "DefaultDirectory", "").ToString();
                        this.Text = doesKeyExist.GetValue("DefaultDirectory").ToString();
                    }
                    else
                    {
                        RegistryKey newKey = Registry.CurrentUser.CreateSubKey(@"Software\VB and VBA Program Settings\Send\General");
                        newKey.SetValue("DefaultDirectory", @"\\blah\blah\blah");
                        myGlobalVars.gsDirectory = Registry.GetValue(@"HKEY_CURRENT_USER\Software\VB and VBA Program Settings\Send\General", "DefaultDirectory", "").ToString();
                        this.Text = myGlobalVars.gsDirectory.ToString();
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show("Building Registry Tree/Key ERROR: 'frmSend_Load' method: " + ex.Message.ToString());
                    writeToLogFile(ex.Message.ToString());
                }
                this.Text = "SENDGL Upload Utility (" + myGlobalVars.gsDirectory.ToString() + ")";

                RefreshFileList(true, false);
                myGlobalVars.gbIgnoreRefresh = false;
            }
            catch (Exception ex)
            {
writeToLogFile(ex.Message.ToString());
            }
        } 

Open in new window


            This will ensure you're reading the CommandLine correctly.  after that you can step through to troubleshoot where that error is coming from.  

Also check the value of: myGlobalVars.gsDirectory
0
 
LVL 1

Author Comment

by:mikesExpertExchange
ID: 39786388
@Kyle: what ever the problem is, it is happening before this code (event) happens because after putting in your changes, I never even get to that code (the MessageBox never shows up), and the app doesn't even open up, but that part is not new.
0
 
LVL 1

Author Comment

by:mikesExpertExchange
ID: 39786408
I did find this interesting. When I took the "T" out of the Target field of the properties, and left your code in for the args, and ran it I got the dialog below. What's interesting about this to me, is that I thought it would say: "...SendGL.exe" NOT "...SendGL.vshost.exe". Not sure if that has anything to do with it or not. Just seemed odd, odd enough to mention it, from my point of view.

args loop msg box
0
 
LVL 39

Accepted Solution

by:
Kyle Abrahams earned 500 total points
ID: 39786499
is FrmSend the first or only form?  Do you have any application startup code?
0
 
LVL 1

Author Comment

by:mikesExpertExchange
ID: 39786623
@Kyle: there was some other start up code. I cleaned it up and now. if i put a parameter in the target property, it has to be surrounded by double quotes or the app wont open up. i've tried surrounding everthing with quotes (single or double) but when i click apply, I get this:

surrounding in quotes
if I leave off the parameter, it will show the args which is the path to the exe on my machine. it still doesn't seem to know how to pick up the argument. also if i don't put any quotes around anything, but put in a parameter, the executable, when double clicked to open up, won't open.
0
 
LVL 1

Author Comment

by:mikesExpertExchange
ID: 39786661
@Kyle: Nevermind. I figured it out. Thank you for your help. I do appreciate it.
0
 
LVL 1

Author Closing Comment

by:mikesExpertExchange
ID: 39786663
Thank you.
0
 
LVL 39

Expert Comment

by:Kyle Abrahams
ID: 39786674
First try it with the command prompt as that's the most direct way to input your "T" into the GL for now.

Once you get that working you should be able to use:

"c:\Dev\SendGL\bin\release\SendGL.exe" T

for your target.
0
 
LVL 39

Expert Comment

by:Kyle Abrahams
ID: 39786676
You should post your solution for anyone else coming across this thread, glad you got it though.
0
 
LVL 1

Author Comment

by:mikesExpertExchange
ID: 39786732
@Kyle: Agreed. Ultimately, the other start up code was just not opening the form after it found the args. There was some if else branching that took it out of the code before the frmSend frmSend1 = new frmSend() and frmSend1.ShowDialog() code was hit. Once i put that code in place it worked fine. Ultimately it was your prompting me to look for other start up code. So I would recommend that all start up code be thoroughly examined if this probem is encountered. Thanks again.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Does the idea of dealing with bits scare or confuse you? Does it seem like a waste of time in an age where we all have terabytes of storage? If so, you're missing out on one of the core tools in every professional programmer's toolbox. Learn how to …
Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
An introduction to basic programming syntax in Java by creating a simple program. Viewers can follow the tutorial as they create their first class in Java. Definitions and explanations about each element are given to help prepare viewers for future …
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now