C# Console.Read,防止用户使用特殊字符

huangapple go评论84阅读模式
英文:

C# Console.Read, prevent use of special characters by user

问题

Is there a way to limit free-text when using Console.ReadLine(); to prevent the use of special characters such as / , % ,$ , #. Currently I allow all characters and then use a .Replace("special character","") to get rid of any.

Here is an example of my code

Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("请在下面键入模型的" + reqVariables[h] + ":");
Console.ForegroundColor = ConsoleColor.Magenta;
freeTextSerialNumbers = Console.ReadLine();

英文:

Is there a way to limit free-text when using Console.ReadLine(); to prevent the use of special characters such as / , % ,$ , #. Currently I allow all characters and then use a .Replace("[special character","") to get rid of any.

Here is an example of my code

                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("Please  type-in the " + reqVariables[h] + " of the model  below:");
                Console.ForegroundColor = ConsoleColor.Magenta;
                freeTextSerialNumbers = Console.ReadLine();

答案1

得分: 1

你可以在循环中使用 Console.ReadKey(true),并选择从控制台中删除这些字符,同时显示其他字符。

类似这样:

public static string ReadLine()
{
    var builder = new StringBuilder();

    while (true)
    {
        var key = Console.ReadKey(true);

        if (key.Key == ConsoleKey.Enter)
        {
            return builder.ToString();
        }
        else
        {
            switch (key.KeyChar)
            {
                case '%':
                case '$':
                case [...] //在这里添加所有不想要的字符
                    break;
                default:
                    builder.Append(key.KeyChar);
                    Console.Write(key.KeyChar);
                    break;
            }
        }
    }
}
英文:

You could use Console.ReadKey(true) in a loop and choose to eliminate those characters from the console while echoing others

Something like this

public static string ReadLine()
{
    var builder = new StringBuilder();

    while (true)
    {
        var key = Console.ReadKey(true);

        if (key.Key == ConsoleKey.Enter)
        {
            return builder.ToString();
        }
        else
        {
            switch (key.KeyChar)
            {
                case '%':
                case '$':
                case [...] //add here all unwanted characters
                    break;
                default:
                    builder.Append(key.KeyChar);
                    Console.Write(key.KeyChar);
                    break;
            }
        }
    }
}

huangapple
  • 本文由 发表于 2023年7月31日 22:53:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76804803.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定