String Manipulation - filepath manipulation


#1

I would like to use the split function and replace function, but I’m having trouble using the split function to remove just the “1234_2” from the variable containing a CSV file path.

Example:
Variable containing the CSV file path = “C:\folder\1234_2.csv”
Variable containing the PDF file path = “C:\folder\images\5678.pdf”

First, I want to assign a new variable with “1234_2” from the CSV file path variable.
Then, I want to replace “5678” with the variable containing “1234_2”.

Any suggestions would be great.


#2

Hi Ben,

There’s many ways to skin a cat, so to speak. What I’d suggest first is looking at the pattern. Is the CSV file path and naming convention always going to stay the same, likewise for the pdf? Because then a simple solution would be the substring function i.e. yourCSVVariable.Substring(10,6). However this wouldn’t be the optimal approach.


#3

Here is my approach:

Assign newpath = Path.Combine(Path.GetDirectoryName(pdfpath),Path.GetFileNameWithoutExtension(csvpath)+".pdf")

So it uses GetDirectoryName to get folder name from your pdf path, then uses GetFileNameWithoutExtension to get filename of your csvpath, and finally uses Combine to join the folder with the filename.

Regards.


#4
You can try following:

string input = @"C:\folder\1234_2.csv";
string[] strArr = input.Split('\\');
string newStr = strArr[0] +"\\"+ strArr[1] + "\\" + "images\\5678" + ".csv";

#5

Yea, this is great. I didn’t realize there were so many standard functions for path. Could this also be accomplished using regex? I’m wondering if I should learn regex or not.


#6

Like you said, using indexes wouldn’t be the way to go for this particular situation. The paths won’t always match the number of indexes.


#7

It’s worth learning Regex, because it can be helpful. But, for filepaths, it’s better to use the Path functions available in .net in System.IO.Directory, System.IO.Path, or System.IO.File, which are the most common ones I use.


#8

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.