Path.GetInvalidFileNameChars() 獲取系統非法字符數組。IndexOfAny 檢查是否包含任一非法字符。using System.IO;
string name = txtTemplateName.Text.Trim();
// 1. 非空
if (string.IsNullOrWhiteSpace(name))
{
MessageBox.Show("請輸入模板名稱!", "提示");
txtTemplateName.Focus(); return;
}
// 2. 非法字符檢測
char[] invalid = Path.GetInvalidFileNameChars();
// 包含: \ / : * ? " < > | 等
if (name.IndexOfAny(invalid) >= 0)
{
MessageBox.Show("名稱包含非法字符:\\ / : * ? \" < > |", "錯誤");
txtTemplateName.Focus(); return;
}
// 3. 可選:長度限制、保留名檢查 (CON, PRN, AUX, NUL...)
if (name.Length > 255) { /* ... */ }
Path.GetInvalidPathChars() // 返回路徑非法字符 (子集不同)
文件名非法字符集包含路徑非法字符,通常僅需檢測文件名字符集。
KeyPress 事件攔截非法鍵。/ 和 \0)。