简体   繁体   中英

How to retrieve characters before and after a forward slash

I have this string which comes from the datareader: http://win-167nve0l50/dev/dev/new/1st Account

I want the get the file name, which is "1st Account" and the list name, which is "new" and the list address which is " http://win-167nve0l50/dev/dev/ ". This is the code I am using: How do I retrieve the site address and the list name.

//getting the file URL from the data reader
string fileURL = dataReader["File URL"].ToString();

//getting the list address/path 
string listAdd = fileURL.Substring(fileURL.IndexOf("/") + 1);

//getting the file name
 string fileName = fileURL.Substring(fileURL.LastIndexOf("/") + 1);

You can get all sorts of info easily using the Uri Class

var uri = new Uri(dataReader["File URL"].ToString());

then you can get various bits from the Uri object eg.

  • Uri.Authority - Gets the Domain Name System (DNS) host name or IP address and the port number for a server.
  • Uri.Host - Gets the host component of this instance
  • Uri.GetLeftPart() - Gets the specified portion of a Uri instance.

If dealing with Uri, use the according class ...

Uri u = new Uri(dataReader["File URL"].ToString());

... and access the desired parts of the path by Segments array

string listAdd = u.Segments[3]; // remove trailing '/' if needed
string fileName = u.Segments[4];

... or in case you need to make sure to handle arbitrary path length

string listAdd = u.Segments[u.Segments.Length - 2];
string fileName = u.Segments[u.Segments.Length - 1];

You should use the Uri class
It's main purpose is to handle composed resource string s.

You can use:

  • Uri.Host to obtain the host address string

  • PathAndQuery to getthe absolute path of the file on the server and the query information sent with the request

All the properties here

You can also do it with Regex :

string str = "http://win-167nve0l50/dev/dev/new/1st Account";
Regex reg = new Regex("^(?<address>.*)\\/(?<list>[^\\/]*)\\/(?<file>.*)$");
var match = reg.Match(str);
if (match.Success)
{
    string address = match.Groups["address"].Value;
    string list = match.Groups["list"].Value;
    string file = match.Groups["file"].Value;
}

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