loris02
loris02

Reputation: 39

How to split a string in c# with a variable?

I can't split a string with a variable:

string directoryName = Path.GetDirectoryName(Global.filepath);
string relativePath = ofd.FileName.Split(directoryName);

I get this error for directoryName: "Argument 1: cannot convert from 'string' to 'char'"

Has anyone an other idea? Thanks for the help.

Upvotes: 0

Views: 189

Answers (4)

Steven Lemmens
Steven Lemmens

Reputation: 720

There is a specific overload you can use for this.

Try something like

ofd.FileName.Split(directoryName, StringSplitOptions.None);

or

ofd.FileName.Split(new string[] { directoryName }, StringSplitOptions.None);

Upvotes: 2

Pavel Sem
Pavel Sem

Reputation: 1753

Good start is as usual to read documentation. There you see many overloads of string.split method.

In your case you try to use

public string[] Split (string separator, StringSplitOptions options = System.StringSplitOptions.None);

but it return string[] not string

string[] path = ofd.FileName.Split(directoryName)

Upvotes: 0

Kaveesh
Kaveesh

Reputation: 398

Google is your friend.

https://learn.microsoft.com/en-us/dotnet/api/system.string.split?view=netcore-3.1#System_String_Split_System_String_System_StringSplitOptions_

The above will help

string[] relativePath = ofd.FileName.Split(directoryName, StringSplitOptions.None);

Upvotes: 0

Hien Nguyen
Hien Nguyen

Reputation: 18975

You can use this overloading of Split string Split(String[], StringSplitOptions)

var relativePath = ofd.FileName.Split(new string[] { directoryName}, StringSplitOptions.None);

Upvotes: 0

Related Questions