问题
I'm trying to recursively create a bunch of directories and certain directory names have ':' characters in which throws the above exception. I was hoping there may be a way to avoid this? Below is a snip of the code I'm using:
foreach (TagLib.File tagFile in tagFiles)
{
GetInfo(tagFile, targetDir);
if (!Directory.Exists(TargetFullPath))
{
Directory.CreateDirectory(TargetFullPath);
System.IO.File.Copy(FilePath, TargetFullPath + "\\" + tagFile.Tag.Title + TargetExt);
} ...
Where 'TargetFullPath' = "G:\Users\Jon\Desktop\musictest\Journey\Journey: Greatest Hits"
Many Thanks :)
回答1:
Colons are one of those characters you just can't use, but you could replace it easily enough. To also make sure you only replace characters in the file name portion (so you don't wipe out the backslashes making up the rest of the file path), you could use:
Path.Combine(Path.GetDirectoryName(TargetFullPath),Path.GetFileName(TargetFullPath).Replace(":","_"));
Assuming there could be other illegal characters in the file name (see this list), you'll want something more robust like a Regex statement.
来源:https://stackoverflow.com/questions/7424274/avoiding-notsupportedexception-using-createdirectory-in-c-sharp