This is what I have so far, but I can't find anywhere the code to say that I just want to include letters and numbers. I'm not familiar with regular expressions. Right now my code just ignores the while loop even if I include '#'.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void okBtn_Click(object sender, EventArgs e)
{
if(textBox1.Text.Contains(@"^[^\W_]*$"))
{
fm1.txtFileName = textBox1.Text;
this.Close();
}
else
{
MessageBox.Show("Filename cannot include illegal characters.");
}
}
}
You can use the method char.IsLetterOrDigit to check whether a input string only contains letters or digits:
if (input.All(char.IsLetterOrDigit))
{
//Only contains letters and digits
...
}
As you're checking for invalid filenames, I'd use Path.GetInvalidPathChars instead:
char[] invalidChars = Path.GetInvalidPathChars();
if (!input.All(c => !invalidChars.Contains(c)))
{
//invalid file name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With