开发者

Replacing process arguments for a C# application

开发者 https://www.devze.com 2023-03-19 14:04 出处:网络
Is there a way to replace the values of the arguments of a managed process like it can be done for a native program as described here?

Is there a way to replace the values of the arguments of a managed process like it can be done for a native program as described here?

Here's a program I wrote trying to do the same thing but it didn't work like the other case:

        static void Main(string[] args)
        {
            if (args == null) 
            { 
                return; 
            }

            foreach (String arg in args)
            {
                Console.WriteLine("Before: " + arg); 

                unsafe
                {
                    fixed (char* ptr = arg)
                    {
                        for (int i = 0; i < arg.Length; i++)
                        {
                            *(ptr + i) = 'x';
                        }
                    }
                }

                Console.WriteLine("After: " + arg); 
            }

            Console.WriteLine("Environment.GetCommandLineArgs(): ");

            foreach (String arg in Environment.GetCommandLineArgs())
            {
                Console.WriteLine(arg);
            }
        }

And the result is开发者_Python百科:

Before: asdf
After: xxxx
Before: lkjasdf
After: xxxxxxx
Before: ;lkajsdf
After: xxxxxxxx
Environment.GetCommandLineArgs():
ConsoleApplication2.exe
asdf
lkjasdf
;lkajsdf

Thank you in advance.


Environment.GetCommandLineArgs() likely makes use of the native GetCommandLine() on Windows. However, the return value will be marshaled into .Net strings and will have no effect on the native pointer actually returned by GetCommandLine().

You should assume this is read-only and that you have no guarantees writing to the pointer won't cause a fault. I'm sure you could use a P/Invoke definition of GetCommandLine() and an IntPtr to overwrite the command line, but this is undefined behavior and isn't guaranteed to work in the future (these sort of assumptions are what Raymond often points out in his articles).

0

精彩评论

暂无评论...
验证码 换一张
取 消