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

3

14

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.:!

Monies answered 3/9, 2013 at 16:4 Comment(6)
What is " NorA.sn.labl[i]"?Critter
Why don't you use Sytem.IO.Path.Combine() ?Kilk
@Critter : is a stringMonies
@Kilk : What is the difference ???Monies
@SaberMalekzadeH like literally "a string", or the type is a tring... if so, what's it's value? Something like "\\whatever"? or "w:\"Critter
@SaberMalekzadeH, e.g you don't have to worry about any backslashes.Kilk
U
19

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.

Upside answered 3/9, 2013 at 16:4 Comment(2)
This describes why it's not working, but what's the solution?Aronoff
In case anyone comes across this: The path given to DirectoryInfo.GetFiles() is a relative path below the object's directory. Absolute paths won't work.Incentive
W
6

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);
}
Wilterdink answered 31/8, 2016 at 13:42 Comment(1)
In my case, I can't use the static version because the "new DirectoryInfo()" method gives me the FileInfo also so that I can choose the most recent file. What's the solution that avoids using the static versions of these methods?Aronoff
W
1

The solution is to not put the full file path in the argument.

You already have the path of the parent directory as the object, so you only need to list the new directory name as an argument.

tld = labdi.CreateSubdirectory(NorA.sn.labl[i]);
Whiskey answered 28/1, 2021 at 20:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.