2012-08-28 162 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, ""); 
} 

相關問題