【发布时间】:2014-12-11 12:23:18
【问题描述】:
我有以下格式的字符串:
"arg1" "arg2" "arg3" ... "argx"
我将使用这个字符串作为我程序的命令行参数的string[]。
如何把这个字符串变成字符串数组?
【问题讨论】:
-
使用任何可用的命令行解析器
标签: c# string command-line-arguments arrays
我有以下格式的字符串:
"arg1" "arg2" "arg3" ... "argx"
我将使用这个字符串作为我程序的命令行参数的string[]。
如何把这个字符串变成字符串数组?
【问题讨论】:
标签: c# string command-line-arguments arrays
自己实现所有的转义并不容易,尤其是CLR为你做的方式。
因此,您最好查看 CLR 源代码。 It mentionsCommandLineToArgvW api 有一个nice documentation。
但我们是 C# 人,必须search this function signature here。幸运的是,它有一个很好的样本(我的样式):
internal static class CmdLineToArgvW
{
public static string[] SplitArgs(string unsplitArgumentLine)
{
int numberOfArgs;
var ptrToSplitArgs = CommandLineToArgvW(unsplitArgumentLine, out numberOfArgs);
// CommandLineToArgvW returns NULL upon failure.
if (ptrToSplitArgs == IntPtr.Zero)
throw new ArgumentException("Unable to split argument.", new Win32Exception());
// Make sure the memory ptrToSplitArgs to is freed, even upon failure.
try
{
var splitArgs = new string[numberOfArgs];
// ptrToSplitArgs is an array of pointers to null terminated Unicode strings.
// Copy each of these strings into our split argument array.
for (var i = 0; i < numberOfArgs; i++)
splitArgs[i] = Marshal.PtrToStringUni(
Marshal.ReadIntPtr(ptrToSplitArgs, i * IntPtr.Size));
return splitArgs;
}
finally
{
// Free memory obtained by CommandLineToArgW.
LocalFree(ptrToSplitArgs);
}
}
[DllImport("shell32.dll", SetLastError = true)]
private static extern IntPtr CommandLineToArgvW(
[MarshalAs(UnmanagedType.LPWStr)] string lpCmdLine,
out int pNumArgs);
[DllImport("kernel32.dll")]
private static extern IntPtr LocalFree(IntPtr hMem);
}
PS。请注意,可执行文件名称应该是该行中的第一个参数。
【讨论】:
【讨论】: