Search code examples
c#.net-4.0command-line-arguments

passing new lines in command line argument?


I loaded up a small console app that simply reads and prints the first command line argument passed to the program to the console.

I want to pass a newline to the argument I tried this:

prog.exe \n  --> outputs \n
prog.exe "sfs \n sfff" --> outputs sfs \n sfff
prog.exe "ff \\n ff" --> outputs ff \\n ff
prog .exe "ff \\\\n ff" --> outputs ff \\\\n ff

Is there some other escaping I'm suppose to use? Or is there some function I have to call on args[0] to process escaped characters before outputting it to the console?

To clarify, I'm trying to pass a string to my program that has newlines in it. The outputting to console was being used as a test. I could have just as easily inserted a debug break line and inspect the contents of the variable.


Solution

  • The problem you're having is that the strings you get from the command line are not compiled. When you have string literals in your code they are compiled and this is when escape characters are processed and converted into newlines etc. You will probably have to do something like replacing all instances of "\n" in your input string with a newline character.

    Edit:

    From here (with minor modifications), this will compile your string using the CSharp compiler thus replacing the escape sequences with the appropriate characters:

        public static string ParseString(string input)
        {
            var provider = new Microsoft.CSharp.CSharpCodeProvider();
            var parameters = new System.CodeDom.Compiler.CompilerParameters()
            {
                GenerateExecutable = false,
                GenerateInMemory = true,
            };
    
            var code = @"
            public class TmpClass
            {
                public static string GetValue()
                {
                    return """ + input + @""";
                }
            }";
    
            var compileResult = provider.CompileAssemblyFromSource(parameters, code);
    
            if (compileResult.Errors.HasErrors)
            {
                throw new ArgumentException(compileResult.Errors.Cast<System.CodeDom.Compiler.CompilerError>().First(e => !e.IsWarning).ErrorText);
            }
    
            var asmb = compileResult.CompiledAssembly;
            var method = asmb.GetType("TmpClass").GetMethod("GetValue");
    
            return method.Invoke(null, null) as string;
        }