using System; using System.IO; using System.Text.RegularExpressions; namespace DemoSolution { class Program { static void Main(string[] args) { string badFileName = @"This!has*INVALID:characters.txt"; string goodFileName = @"This-has_INVALID.characters.txt"; Console.WriteLine("badFileName = {0}", badFileName.IsValidFileName()); // OUTPUT: badFileName = False Console.WriteLine("goodFileName = {0}", goodFileName.IsValidFileName()); // OUTPUT: goodFileName = True } } public static class MyExtensions { ////// Checks the string to see if any invalid characters exist for a file name. /// /// ////// Returns "True" if the file name has no invalid /// characters, else it returns "False". /// ////// string fileName = "Valid_File-Name.txt"; /// public static bool IsValidFileName(this string FileName) { // Create the RegEx pattern to match Regex BadPathCharacters = new Regex( "[" + Regex.Escape(String.Join("", Path.GetInvalidFileNameChars())) + "]"); // See if any of the characters are a match. if (BadPathCharacters.IsMatch(FileName)) { return false; } return true; } } }
Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts
Friday, April 10, 2015
File Name Validation
In a continuing effort to keep track of my coding notes, here is another function I wrote that I use a lot. It uses "Path" to get a list of invalid characters to check against.
Tuesday, December 9, 2014
When I need to allow only Net Bios characters I use this function. It can be used to make sure a user enters a proper server name.
////// Will allow text entered into a textbox to be Net Bios safe. /// If the key pressed is not good, it is fake handled. /// /// Can be called from XAML like so: /// /// /// public static void NetBiosAllowedTextOnly(object sender, TextCompositionEventArgs e) { // Get the entered text string TheText = e.Text; //////////////////////////////////////////////////////////////////////////// // NetBIOS computer names cannot contain the following characters: // // • backslash (\) • slash mark (/) // // • colon (:) • asterisk (*) // // • question mark (?) • quotation mark (") // // • less than sign (<) • greater than sign (>) // // • vertical bar (|) // //////////////////////////////////////////////////////////////////////////// if (-1 < TheText.IndexOfAny(new char[] { '\\', '/', ':', '*', '?', '\"', '<', '>', '|' })) { // Not allowed character so pretend it was handled. e.Handled = true; } else { // Allowed character, let it be handled regularly. e.Handled = false; } }/// /// NOTE: PreviewTextInput is WPF Device safe as compared to checking the keyboard. ///
Subscribe to:
Posts (Atom)