views:

38

answers:

2

Hello,

How would I get the directory and filename from the following string using C#:

string test = "[email protected], snap555.jpg, c:\users\test\desktop\snap555.jpg";

I only want to be able to get the "c:\users\test\desktop\snap555.jpg" from the string and turn it into another string.

The characters before the "," will always be different and different lengths such as: "[email protected], x.txt, c:\users\test\desktop\x.txt"

What is the easiest way to do this in c#?

Thanks.

t

+3  A: 

If the comma delimiter does not appear in the first part, you can use:

string pathName = test.Split(',')[2];

If that space after the comma is a problem and assuming that the first part never has spaces, you can use:

char[] delims = new char[] { ',', ' '};
string pathName = test.Split(delims, StringSplitOptions.RemoveEmptyEntries)[2];

This example assumes you always want the third item, as mentioned in your question. Otherwise, change the 2 in the examples above to the correct index of the item you want. For example, if it should always be the last item, you can do:

char[] delims = new char[] { ',', ' '};
string[] items = test.Split(delims, StringSplitOptions.RemoveEmptyEntries);
string pathName = items[items.Length-1];
Michael Goldshteyn
+1 for more detail than me. :)
EJC
+2  A: 

If there's always going to be a comma there you can use

string test = "snap555.jpg, c:\users\test\desktop\snap555.jpg";
string[] parts = test.Split(',');

Then get whatever you need from the parts array.

EJC