Dot-Net
如何檢查路徑中的非法字元?
有沒有辦法在.Net中檢查用於路徑的字元串是否包含無效字元?我知道我可以遍歷 Path.InvalidPathChars 中的每個字元以查看我的 String 是否包含一個字元,但我更喜歡一個簡單的,也許更正式的解決方案。
有嗎?
我發現如果我只檢查 Get,我仍然會遇到異常
更新:
我發現 GetInvalidPathChars 並沒有涵蓋每個無效的路徑字元。GetInvalidFileNameChars 還有 5 個,包括我遇到的“?”。我將切換到那個,如果它也被證明是不充分的,我會報告。
更新 2:
GetInvalidFileNameChars 絕對不是我想要的。它包含’:’,任何絕對路徑都將包含它(“C:\whatever”)。我想我畢竟只需要使用 GetInvalidPathChars 並添加“?” 以及任何其他在出現時給我帶來問題的角色。歡迎更好的解決方案。
不推薦使用 InvalidPathChars。請改用 GetInvalidPathChars():
public static bool FilePathHasInvalidChars(string path) { return (!string.IsNullOrEmpty(path) && path.IndexOfAny(System.IO.Path.GetInvalidPathChars()) >= 0); }編輯:稍長,但在一個函式中處理路徑與文件無效字元:
// WARNING: Not tested public static bool FilePathHasInvalidChars(string path) { bool ret = false; if(!string.IsNullOrEmpty(path)) { try { // Careful! // Path.GetDirectoryName("C:\Directory\SubDirectory") // returns "C:\Directory", which may not be what you want in // this case. You may need to explicitly add a trailing \ // if path is a directory and not a file path. As written, // this function just assumes path is a file path. string fileName = System.IO.Path.GetFileName(path); string fileDirectory = System.IO.Path.GetDirectoryName(path); // we don't need to do anything else, // if we got here without throwing an // exception, then the path does not // contain invalid characters } catch (ArgumentException) { // Path functions will throw this // if path contains invalid chars ret = true; } } return ret; }