пусть к файлу через командную строку C#

Допустим вот так всё отлично отрабатывает

var path = @"D:\FoxMinded\calculator-project\Calculator\numbersForCalculate.txt";
FromFile(path);

когда хочу передать путь к файлу через командную строку

код :

if (args.Length > 0)
            {
                var path = args[0];
                FromFile(path);
            } 

в консоли :

"D:\hekeemje\calculator-project\Calculator\Calculator\bin\Debug\net5.0\Calculator.exe" "D:\hekeemje\calculator-project\Calculator\numbersForCalculate.txt"

тогда выбивает ошибку

Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
   at Calculator.Program.FromFile(String path) in D:\FoxMinded\calculator-project\Calculator\Calculator\Program.cs:line 53
   at Calculator.Program.Main(String[] args) in D:\FoxMinded\calculator-project\Calculator\Calculator\Program.cs:line 15

P.S. если пытаюсь сделать

var path = "D:\FoxMinded\calculator-project\Calculator\numbersForCalculate.txt";

тогда ругается и надо добавить "@"перед путем , может быть в этом проблема что в консоли оно принимает без "@" ?

Полностью код :

internal static class Program
    {
        private static readonly CalcOperations calculator = new CalcOperations();

        public static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                var path = args[0];
                FromFile(path);
            }
            else
            {
                while (true)
                {
                Console.WriteLine("Type what you need to calculate : ");
                string userText = Console.ReadLine();
                FromUser(userText);
                }
            }

            Console.ReadKey();
        }

        private static void FromUser(string text)
        {
            try
            {
                var result = calculator.ProcessStart(text);
                Console.WriteLine($"Result : {result}");
            }
            catch (DivideByZeroException ex)
            {
                Console.WriteLine(ex.Message);
            }

            catch (Exception)
            {
                Console.WriteLine("You typed something wrong.");
            }
        }

        private static void FromFile(string path)
        {
            if (File.Exists(path))
            {
                string[] str = File.ReadAllLines(path);
                var resultFile = new DirectoryInfo(Directory.GetCurrentDirectory()).Parent.Parent.Parent.Parent + @"\resultOfCalculate.txt";

                using (StreamWriter stream = new StreamWriter(resultFile))
                {
                    for (var i = 0; i < str.Length; i++)
                    {
                        try
                        {
                            stream.WriteLine(str[i] + " = " + calculator.ProcessStart(str[i]));
                        }
                        catch (DivideByZeroException ex)
                        {
                            stream.WriteLine(str[i] + " = " + ex.Message);
                        }
                        catch (Exception)
                        {
                            stream.WriteLine(str[i] + " = You have mistake.");
                        }
                    }
                }
            }
            else
            {
                Console.WriteLine("Can't find your file, please write correct way to file.");
            }
        }
    }
}

Ответы (1 шт):

Автор решения: aepot
public static void Main(string[] args)

Уберите public.

От монстра .Parent.Parent.Parent.Parent надо избавитья. Давайте так

var resultFile = Path.Combine(Path.GetDirectoryName(path), "resultOfCalculate.txt");

Файл результатов будет записан туда же, в ту же папку, откуда был прочитан исходный

И кавычки сами магическим образом никуда не денутся

var path = args[0].Trim('"');
→ Ссылка