简体   繁体   中英

Get a file/directory path from a string that contains other data

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

string test = "test@test.com, 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: "bob@bob.com, x.txt, c:\\users\\test\\desktop\\x.txt"

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

Thanks.

t

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];

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM