If string path = "\\ProgFiles\\sampleDir\\annet.dll" I want to take "\\ProgFiles\\sampleDir" alone from the path in a seperate string variable using c#. Do I have any inbuilt option for this? I am using visual studio 2008 and .net compact framework.
4 Answers
string directory = Path.GetDirectoryName(path);
Be aware that there are some nuances with this method (like returning null for a root directory): check out the MSDN.
1 Comment
Badhri Ravikumar
And do I have any option of retrieving sampleDir alone from path??
Take a look at the System.IO.Path class. It contains a Method "GetDirectoryName". That's what you should need.
Comments
You can use the FileInfo class to do that, just try something like this
FileInfo fi = new FileInfo("Your path here"); string dirName = fi.DirectoryName; Comments
You could try:
String path = "C:\\ProgFiles\\SampleDir\\annet.dll"; String newPath = path.Substring(0, path.LastIndexOf("\\")); The syntax may be a little out (i have not tested it), but definitely look up .Substring and .LastIndexOf methods on strings!
2 Comments
Yngve B-Nilsen
No stringparsing. The other answers point to System.IO.Path which is what you should use.
Joey
Indeed. One reason would be that the
Path methods work correctly with forward slashes, too.