给.NET的string类添加一个命令行参数分解的扩展
时间:2011-01-12 来源:qiaojie
代码如下:
using System.Runtime.InteropServices;
using System.Text;
/// <summary>
/// string extension for split command line to string[]
/// </summary>
public static class CmdLineExtension
{
public static string[] SplitArgs(this string cmd)
{
int count;
var ret = CommandLineToArgvW(cmd, out count);
if(ret == IntPtr.Zero)
throw new ArgumentException("Unable to split argument.");
try
{
var results = new string[count];
for(int i = 0; i < count; i++)
results[i] = Marshal.PtrToStringUni(Marshal.ReadIntPtr(ret, i * IntPtr.Size));
return results;
}
finally
{
LocalFree(ret);
}
}
[DllImport("shell32.dll", SetLastError = true)]
static extern IntPtr CommandLineToArgvW([MarshalAs(UnmanagedType.LPWStr)]string cmd, out int count);
[DllImport("kernel32.dll")]
static extern IntPtr LocalFree(IntPtr mem);
}
相关阅读 更多 +
排行榜 更多 +