2012-08-28 117 views
0

可能重复:
How check if given string is legal (allowed) file name under Windows?C#删除不允许的文件夹名称的字符

找遍了一下,花了几分钟谷歌搜索,但我不能把我所发现,我的背景。 。

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

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

所以,我检索projectNameBox.Text和与文本创建一个文件作为文件名,但如果我包括一个:,或一个\或一个/等..它只会崩溃,这是正常的,因为这些是不允许的文件夹名称..我如何检查文本,创建文件之前,并删除角色,甚至更好,什么都不做,并建议用户他不能使用这些角色? 预先感谢

+0

是否使用的WinForms或WPF? –

+0

System.IO.Path.GetInvalidPathChars(): – eulerfx

+0

我正在使用Windows窗体,抱歉没有指定!和eulerfx..how我可以适应这种情况下..这让我困惑! –

回答

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"); 
} 

替代有在第一评论提供的链接一个正则表达式的例子。

+0

非常感谢kind sirs :) –

1

您可以从您的projectNameBox文本框中响应TextChanged事件来拦截对其内容所做的更改。这意味着您可以在稍后创建路径之前删除所有无效字符。

要创建的事件处理程序,请单击在设计你的projectNameBox控制,点击Events图标Properties窗口,在出现在下面的列表中TextChanged事件然后双击。下面是一些代码,剔除无效字符一个简单的例子:(你需要一个using语句System.Text.RegularExpressions在你的文件的顶部,太)

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, ""); 
} 

相关问题