Mason Ticehurst
Mason Ticehurst

Reputation: 474

C# Remove x Number of Parent Directories from String

I am reading several files from a directory and inserting their path into an array of strings like so:

string[] file_tree = Directory.GetFiles(Path.GetDirectoryName(file_path), "*.*", SearchOption.AllDirectories);

Each element in the array looks like:

C:\\filepath1\\filepath2\\filepath3\\filepath4\\file.txt

I would like them to end up looking like this:

\\filepath3\\filepath4\\file.txt

Note: In my case, the names of the parent directories (filepath1, filepath2, etc) are not always the same.

What is the most efficient way to remove the top X amount of parent directories?

Upvotes: 1

Views: 47

Answers (1)

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34160

int x = 2;
file_tree = file_tree.Select(a => string.Join("\\",a.Split('\\').Skip(x).ToArray())).ToArray();

Explanation:

a.Split('\\') splits the string by \\

.Skip(x) skips x element from it

string.Join("\\", result) joins the items in result with \\ and produce a string

file_tree.Select(a => ...) for each item (a) in the array selects the new produced string

Live Demo

Upvotes: 2

Related Questions