dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
15.47k stars 4.76k forks source link

[API Proposal]: Escaping text from curly braces to create a valid Format string from user-entered text so that they are not treated as formatting elements #108238

Open AlexRadch opened 2 months ago

AlexRadch commented 2 months ago

Background and motivation

When I create a Format string from user-entered text, I need a method to escape the curly braces "{" and "}" so that they are not treated as formatting elements.

string fileName = "c:\\path\\filename{123}.txt"; // Can contains curly braces `{` and `}`

var fullFileNameWithoutExtension = Path.Combine(Path.GetDirectoryName(fileName)!, Path.GetFileNameWithoutExtension(fileName));
var fileExt = Path.GetExtension(fileName);

int partsCount = 10;
int partsLength = partsCount.ToString().Length;

var outputFormat = $"{StringEscapeFormat(fullFileNameWithoutExtension)}.{{0:D{partsLength}}}.{{1:D{partsLength}}}{StringEscapeFormat(fileExt)}"; // Format with user-entered text

Console.WriteLine(fileName);
Console.WriteLine(outputFormat);
Console.WriteLine();
Console.WriteLine(string.Format(outputFormat, 5, 10));
Console.WriteLine(string.Format(outputFormat, 10, 10));

// Escape the curly braces "{" and "}" so that they are not treated as formatting elements
string StringEscapeFormat(string text) => new StringBuilder(text).Replace("{", "{{").Replace("}", "}}").ToString();

Run code on sharplab.

API Proposal

namespace System;

public class String
{
    // Escape the curly braces "{" and "}" so that they are not treated as formatting elements
    public string EscapeFormat(string text) => new StringBuilder(text).Replace("{", "{{").Replace("}", "}}").ToString(); // Not optimized implementation
}

API Usage

var userInput = args[0];
var format = $"{string.EscapeFormat(userInput)} {0} {1}";

var result = string.Format(format, 123, 456);

Alternative Designs

No response

Risks

No response

dotnet-policy-service[bot] commented 2 months ago

Tagging subscribers to this area: @dotnet/area-system-runtime See info in area-owners.md if you want to be subscribed.

huoyaoyuan commented 2 months ago

When I create a Format using input text

Using user input as a part of formatting template doesn't sound like a good idea. Though string interpolation is too simple to be vulnerable from injection, it's can also be hard to ensure things are correct.