Second path fragment must not be a drive or UNC name - Create Subdirectory Error

核能气质少年 提交于 2019-12-10 12:46:09

问题


I have an exception in the third line ofthis code "Second path fragment must not be a drive or UNC name"

DirectoryInfo labdi = new DirectoryInfo(Back.mainfolderpath + @"\news\l");
DirectoryInfo tld = new DirectoryInfo(labdi.FullName + @"\" + NorA.sn.labl[i]);
tld = labdi.CreateSubdirectory(labdi.FullName + @"\" + NorA.sn.labl[i] + @"\");

There is no useful way on the web. Thank You.:!


回答1:


I ran into this one today and finally tracked it down.

The exception is trying to tell you that when a DirectoryInfo takes a path as an argument (e.g., CreateSubdirectory or GetFiles), it will object if the path argument contains the Root and throw this elusive exception.

So path arguments that contain "C:\" or "D:\" etc do not work. Armed with this context, the exception message actually makes a bit of sense.

In your code, you were using the FullName property and this string contains "C:\" or whatever the root is.

Given the age of the question, I should add c#, .NET 4.5, VS2013.




回答2:


The easiest solution to this problem is to use the static version of the Directory and File methods. You do not have to remove the root doing it this way. You also do not need the DirectoryInfo or FileInfo objects, they are what giving you headaches

string someFile = @"C:\somefolder\somefile.txt";
string directory = Path.GetDirectoryName(someFile);

foreach(var file in Directory.GetFiles(directory))
{
   File.Delete(file);
}


来源:https://stackoverflow.com/questions/18596774/second-path-fragment-must-not-be-a-drive-or-unc-name-create-subdirectory-error

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