CommandLineSplit.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace pmtest_client
  7. {
  8. public class CommandLineSplit
  9. {
  10. public static IEnumerable<string> SplitArgs(string commandLine)
  11. {
  12. var result = new StringBuilder();
  13. var quoted = false;
  14. var escaped = false;
  15. var started = false;
  16. var allowcaret = false;
  17. for (int i = 0; i < commandLine.Length; i++)
  18. {
  19. var chr = commandLine[i];
  20. if (chr == '^' && !quoted)
  21. {
  22. if (allowcaret)
  23. {
  24. result.Append(chr);
  25. started = true;
  26. escaped = false;
  27. allowcaret = false;
  28. }
  29. else if (i + 1 < commandLine.Length && commandLine[i + 1] == '^')
  30. {
  31. allowcaret = true;
  32. }
  33. else if (i + 1 == commandLine.Length)
  34. {
  35. result.Append(chr);
  36. started = true;
  37. escaped = false;
  38. }
  39. }
  40. else if (escaped)
  41. {
  42. result.Append(chr);
  43. started = true;
  44. escaped = false;
  45. }
  46. else if (chr == '"')
  47. {
  48. quoted = !quoted;
  49. started = true;
  50. }
  51. else if (chr == '\\' && i + 1 < commandLine.Length && commandLine[i + 1] == '"')
  52. {
  53. escaped = true;
  54. }
  55. else if (chr == ' ' && !quoted)
  56. {
  57. if (started) yield return result.ToString();
  58. result.Clear();
  59. started = false;
  60. }
  61. else
  62. {
  63. result.Append(chr);
  64. started = true;
  65. }
  66. }
  67. if (started) yield return result.ToString();
  68. }
  69. }
  70. }