I'm simply adding optional command line argument support to my application using the NuGet package CommandLineParser. I'm passing the Options class object into my main application so i can access the necessary values of the object as needed.
Issue...
- The only reason I've moved the Options class outside of the static class Program, is so i can create a variable in other parts of the application called Options and know of the class Options. In doing so i now get the following error. I've noticed that the Options attribute 'Filepath' returns null when it should technically be an empty string. Why is my Default="" not working properly?
'System.NullReferenceException: 'Object reference not set to an instance of an object. 'Snipper.Options.Filepath.get returned null
using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using CommandLine;
namespace Snipper
{
public class Options
{
[Option('f', "filepath", Default = "", Required = false, HelpText = "Set output path, otherwise save in Pictures/Snipper")]
public string Filepath { get; set; }
[Option('w', "width", Default = 0, Required = false, HelpText = "Final output resolution width in pixels")]
public int Width { get; set; }
[Option('h', "height", Default = 0, Required = false, HelpText = "Final output resolution height in pixels")]
public int Height { get; set; }
}
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
// do not allow multiple instances of the same program
if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)
{
return;
}
// Commandline args
var options = new Options();
Parser.Default.ParseArguments<Options>(args).WithParsed<Options>(opts => options = opts);
if (options.Filepath.Trim() == "")
{
options.Filepath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "Snipper", "screenshot.png");
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm(options));
}
}
}