When accepting input from your user, your program should expect that invalid characters will be entered. For example, your program has a custom file name dialog. You want to quickly detect invalid path characters. So: You can use the Path.GetInvalidFileNameChars and Path.GetInvalidPathChars methods. Tip: You can use the character arrays returned by Path.GetInvalidFileNameChars and Path.GetInvalidPathChars with a Dictionary.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

class Program
{
    static void Main()
    {
 // First, we build a Dictionary of invalid characters.
 var dict = GetInvalidFileNameChars();
 // Next, we test the dictionary to see if the asterisk (star) is valid.
 if (dict.ContainsKey('*'))
 {
     // This will run, because the star is in the Dictionary.
     Console.WriteLine("* is an invalid char");
 }
    }

    /// <summary>
    /// Get a Dictionary of the invalid file name characters.
    /// </summary>
    static Dictionary<char, bool> GetInvalidFileNameChars()
    {
 // This method uses lambda expressions with ToDictionary.
 return Path.GetInvalidFileNameChars().ToDictionary(c => c, c => true);
    }
}
Outpuut

* is an invalid char

0 comments

Related Posts Plugin for WordPress, Blogger...