PasteArguments.Windows.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections.Generic;
  5. using System.Text;
  6. namespace System
  7. {
  8. internal static partial class PasteArguments
  9. {
  10. /// <summary>
  11. /// Repastes a set of arguments into a linear string that parses back into the originals under pre- or post-2008 VC parsing rules.
  12. /// The rules for parsing the executable name (argv[0]) are special, so you must indicate whether the first argument actually is argv[0].
  13. /// </summary>
  14. internal static string Paste(IEnumerable<string> arguments, bool pasteFirstArgumentUsingArgV0Rules)
  15. {
  16. var stringBuilder = new StringBuilder();
  17. foreach (string argument in arguments)
  18. {
  19. if (pasteFirstArgumentUsingArgV0Rules)
  20. {
  21. pasteFirstArgumentUsingArgV0Rules = false;
  22. // Special rules for argv[0]
  23. // - Backslash is a normal character.
  24. // - Quotes used to include whitespace characters.
  25. // - Parsing ends at first whitespace outside quoted region.
  26. // - No way to get a literal quote past the parser.
  27. bool hasWhitespace = false;
  28. foreach (char c in argument)
  29. {
  30. if (c == Quote)
  31. {
  32. throw new ApplicationException("The argv[0] argument cannot include a double quote.");
  33. }
  34. if (char.IsWhiteSpace(c))
  35. {
  36. hasWhitespace = true;
  37. }
  38. }
  39. if (argument.Length == 0 || hasWhitespace)
  40. {
  41. stringBuilder.Append(Quote);
  42. stringBuilder.Append(argument);
  43. stringBuilder.Append(Quote);
  44. }
  45. else
  46. {
  47. stringBuilder.Append(argument);
  48. }
  49. }
  50. else
  51. {
  52. AppendArgument(stringBuilder, argument);
  53. }
  54. }
  55. return stringBuilder.ToString();
  56. }
  57. }
  58. }