0

Possible Duplicate:
How check if given string is legal (allowed) file name under Windows?

I have searched about, spent some minutes googling, but i cant apply what i have found, to my context..

string appPath = Path.GetDirectoryName(Application.ExecutablePath);
        string fname = projectNameBox.Text;
        if (projectNameBox.TextLength != 0)
        {

            File.Create(appPath + "\\projects\\" + fname + ".wtsprn");

So, i am retrieving the projectNameBox.Text and creating a file with the text as filename, but if i include a :, or a \ or a / etc.. it will just crash, which is normal, as those are not allowed for a folder name..How can i check the text, before the file creation, and remove the characters, or even better, do nothing and advise the user that he can not use those characters? Thanks in advance

Community
  • 1
  • 1
Nuno Valente
  • 143
  • 2
  • 12

2 Answers2

1
string appPath = Path.GetDirectoryName(Application.ExecutablePath);
string fname = projectNameBox.Text;

bool _isValid = true;
foreach (char c in Path.GetInvalidFileNameChars())
{
    if (projectNameBox.Text.Contains(c))
    {
        _isValid = false;
        break;
    }
}

if (!string.IsNullOrEmpty(projectNameBox.Text) && _isValid)
{
    File.Create(appPath + "\\projects\\" + fname + ".wtsprn");
}
else
{
    MessageBox.Show("Invalid file name.", "Error");
}

Alternative there is a regex example in the link provided in the first comment.

coolmine
  • 4,427
  • 2
  • 33
  • 45
1

You can respond to the TextChanged event from your projectNameBox TextBox to intercept changes made to its contents. This means that you can remove all the invalid characters before creating your path later on.

To create the event handler, click on your projectNameBox control in the designer, click the Events icon in the Properties window, then double-click on the TextChanged event in the list that appears below. The following is a brief example of some code that strips out invalid characters:

private void projectNameBox_TextChanged(object sender, EventArgs e)
{
    TextBox textbox = sender as TextBox;
    string invalid = new string(System.IO.Path.GetInvalidFileNameChars());
    Regex rex = new Regex("[" + Regex.Escape(invalid) + "]");
    textbox.Text = rex.Replace(textbox.Text, "");
}

(You'll need a using statement for System.Text.RegularExpressions at the top of your file, too.)

Dave R.
  • 7,206
  • 3
  • 30
  • 52