Separate String with .Split - C # [duplicate]

1

Good morning,

I'm trying to get a specific part of a string in Visual Studio, in case the string in question is a directory path: "C: \ Users \ User \ File-2018.txt" I would like to try to get only what comes after the last "\", I tried to do

string[] texto = caminho.Split("\");
string resultado = texto[3];

But the error code, saying that can not convert character to string, could anyone help me in this situation please? Thank you very much in advance. obs: the variable "path" is of type string

    
asked by anonymous 13.08.2018 / 16:16

2 answers

1

Try to use the Substring method, it would look like this:

string resultado = caminho.Substring(caminho.LastIndexOf(@"\") + 1);

Explanation: Substring method has the function of returning some "piece" of our original string. The form we are using requires the start index of our new string, so we use the LastIndexOf method to say we want the index of the last \ in its string + 1 to get from the next character after the last \ .

    
13.08.2018 / 16:19
2

.Split() does not accept double quotation marks, single quotes, ex:

string caminho = @"C:\Users\Usuario\Arquivo-2018.txt";
string[] texto = caminho.Split('\');
string resultado = texto[3]; //Arquivo-2018.txt

Font : .Split()

    
13.08.2018 / 16:38