12
C # Sanitize ชื่อไฟล์
ฉันเพิ่งย้าย MP3 จำนวนมากจากหลาย ๆ ที่ไปยังที่เก็บ ฉันสร้างชื่อไฟล์ใหม่โดยใช้แท็ก ID3 (ขอบคุณ TagLib-Sharp!) และฉันสังเกตว่าฉันได้รับSystem.NotSupportedException: "ไม่รองรับรูปแบบของเส้นทางที่กำหนด" นี้ถูกสร้างขึ้นโดยการอย่างใดอย่างหนึ่งหรือFile.Copy()Directory.CreateDirectory() ใช้เวลาไม่นานในการรู้ว่าชื่อไฟล์ของฉันต้องได้รับการทำให้สะอาด ดังนั้นฉันจึงทำสิ่งที่ชัดเจน: public static string SanitizePath_(string path, char replaceChar) { string dir = Path.GetDirectoryName(path); foreach (char c in Path.GetInvalidPathChars()) dir = dir.Replace(c, replaceChar); string name = Path.GetFileName(path); foreach (char c in Path.GetInvalidFileNameChars()) name = name.Replace(c, replaceChar); return dir …