zoukankan      html  css  js  c++  java
  • 给.NET的string类添加一个命令行参数分解的扩展

    把一个把字符串分解成命令行参数是很常见的操作,一直很纳闷为什么.net没有提供相关的功能,自己写一个又觉得麻烦。幸好windows提供了一个API来干这个事情。不过这个API调用起来颇为麻烦,google了一下才找到方法。代码贴上来,方便后来人使用。

    代码如下:

    using System;
    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);
    }
  • 相关阅读:
    改写promise并添加超时处理
    js将文案复制到剪贴板
    学习笔记(安装、命名实体识别、BERT、面试)
    读书笔记——安装
    Markdown使用
    奔波三载,虽死犹生
    .net工程师的利器
    .NET开发相关技术
    两行代码教你用React useContext代替React-redux
    记解决 `antd is not defined` 解决ant design 打包体积过大的问题
  • 原文地址:https://www.cnblogs.com/Hybird3D/p/1933768.html
Copyright © 2011-2022 走看看