Avoiding NotSupportedException using CreateDirectory in c#

坚强是说给别人听的谎言 提交于 2020-01-05 04:40:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!