Checking a file name and path for invalid characters
If you would like to check a string for invalid File Name or Path characters you can use these built in methods. They are Path.GetInvalidFileNameChars and Path.GetInvalidPathChars
Language: C#
Namespace: System.IO
Method: Path.GetInvalidFileNameChars
Return Type: System.Char[], an array containing the invalid file name characters
Usage:
Char[] invalidchars = Path.GetInvalidFileNameChars(); foreach (char c in invalidchars) { Console.WriteLine(c); } Console.ReadLine(); |
Purpose:
This will fill the array invalidchars with the invalid file name characters. It will then use the foreach loop to output each of the characters to the command line and finally use ReadLine to pause for user input.
Language: C#
Namespace: System.IO
Method: Path.GetInvalidPathChars
Return Type: System.Char[], an array containing the invalid file name characters
Usage:
Char[] invalidchars = Path.GetInvalidPathChars(); foreach (char c in invalidchars) { Console.WriteLine(c); } Console.ReadLine(); |
Purpose:
This will fill the array invalidchars with the invalid path characters. It will then use the foreach loop to output each of the characters to the command line and finally use ReadLine to pause for user input.
Language: C#
In this example project, the form contains a Text Box (textBox1) and a Command Button (button1). When the user clicks the command button each character in the Text Box will be checked against each invalid character (invalidchars). If an invalid character is found, the user will be notified via a Message Box.
Usage:
using System.IO; namespace WindowsFormsApplication { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Char[] invalidchars = Path.GetInvalidFileNameChars(); foreach (char a in textBox1.Text) { foreach (char c in invalidchars) { if (a.ToString() == c.ToString()) { MessageBox.Show("Invalid Character: " + a.ToString()); } } } } } } |
