PasteArguments.Windows.cs 2.5 KB

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