[c#] How do I start a program with arguments when debugging?

I want to debug a program in Visual Studio 2008. The problem is that it exits if it doesn't get arguments. This is from the main method:

if (args == null || args.Length != 2 || args[0].ToUpper().Trim() != "RM") 
{
    Console.WriteLine("RM must be executed by the RSM.");
    Console.WriteLine("Press any key to exit program...");
    Console.Read();
    Environment.Exit(-1);
}

I don't want to comment it out and and then back in when compiling. How can I start the program with arguments when debugging? It is set as the StartUp Project.

The answer is


My suggestion would be to use Unit Tests.

In your application do the following switches in Program.cs:

#if DEBUG
    public class Program
#else
    class Program
#endif

and the same for static Main(string[] args).

Or alternatively use Friend Assemblies by adding

[assembly: InternalsVisibleTo("TestAssembly")]

to your AssemblyInfo.cs.

Then create a unit test project and a test that looks a bit like so:

[TestClass]
public class TestApplication
{
    [TestMethod]
    public void TestMyArgument()
    {
        using (var sw = new StringWriter())
        {
            Console.SetOut(sw); // this makes any Console.Writes etc go to sw

            Program.Main(new[] { "argument" });

            var result = sw.ToString();

            Assert.AreEqual("expected", result);
        }
    }
}

This way you can, in an automated way, test multiple inputs of arguments without having to edit your code or change a menu setting every time you want to check something different.


I would suggest using the directives like the following:

        static void Main(string[] args)
        {
#if DEBUG
            args = new[] { "A" };
#endif

            Console.WriteLine(args[0]);
        }

Good luck!


For Visual Studio Code:

  • Open launch.json file
  • Add args to your configuration:

"args": ["some argument", "another one"],


for .NET Core console apps you can do this 2 ways - from the launchsettings.json or the properties menu.

Launchsettings.json

enter image description here

or right click the project > properties > debug tab on left

see "Application Arguments:"

  • this is " " (space) delimited, no need for any commas. just start typing. each space " " will represent a new input parameter.
  • (whatever changes you make here will be reflected in the launchsettings.json file...)

enter image description here


I came to this page because I have sensitive information in my command line parameters, and didn't want them stored in the code repository. I was using System Environment variables to hold the values, which could be set on each build or development machine as needed for each purpose. Environment Variable Expansion works great in Shell Batch processes, but not Visual Studio.

Visual Studio Start Options:

Visual Studio Start Options

However, Visual Studio wouldn't return the variable value, but the name of the variable.

Example of Issue:

Example of Error in Visual Studio

My final solution after trying several here on S.O. was to write a quick lookup for the Environment variable in my Argument Processor. I added a check for % in the incoming variable value, and if it's found, lookup the Environment Variable and replace the value. This works in Visual Studio, and in my Build Environment.

foreach (string thisParameter in args)
            {
                if (thisParameter.Contains("="))
                {
                    string parameter = thisParameter.Substring(0, thisParameter.IndexOf("="));
                    string value = thisParameter.Substring(thisParameter.IndexOf("=") + 1);

                    if (value.Contains("%"))
                    {   //Workaround for VS not expanding variables in debug
                        value = Environment.GetEnvironmentVariable(value.Replace("%", ""));
                    }

This allows me to use the same syntax in my sample batch files, and in debugging with Visual Studio. No account information or URLs saved in GIT.

Example Use in Batch

Batch File Example


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to visual-studio

VS 2017 Git Local Commit DB.lock error on every commit How to remove an unpushed outgoing commit in Visual Studio? How to download Visual Studio Community Edition 2015 (not 2017) Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio Code pylint: Unable to import 'protorpc' Open the terminal in visual studio? Is Visual Studio Community a 30 day trial? How can I run NUnit tests in Visual Studio 2017? Visual Studio 2017: Display method references

Examples related to visual-studio-2008

Convert Text to Uppercase while typing in Text box SQL Server r2 installation error .. update Visual Studio 2008 to SP1 What is and how to fix System.TypeInitializationException error? Error LNK2019: Unresolved External Symbol in Visual Studio download and install visual studio 2008 Git in Visual Studio - add existing project? Visual Studio can't 'see' my included header files How to insert Records in Database using C# language? If statements for Checkboxes LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

Examples related to visual-studio-debugging

Visual Studio breakpoints not being hit ASP.NET MVC5/IIS Express unable to debug - Code Not Running SSL Connection / Connection Reset with IISExpress How do I start a program with arguments when debugging? Unable to start debugging on the web server. Could not start ASP.NET debugging VS 2010, II7, Win 7 x64