Path.Combine for URLs in C#: what to use instead
Codemia Knowledge Hub ·
Do not use Path.Combine for URLs. It is built for file system paths, so on Windows it joins with a backslash and knows nothing about URL parts like ://, query strings or encoding. Use the Uri class (or UriBuilder), or concatenate the strings yourself while controlling the slash.
What Path.Combine does
Path.Combine takes two or more strings and joins them into one path, inserting directory separators for you, so you avoid error-prone manual concatenation:
Why it breaks URLs
- Separators: File paths use backslashes
\\on Windows and forward slashes/on UNIX-based systems. URLs always use/, whatever the platform. - URL components: URLs contain protocol delimiters (
://), query strings (?) and fragments (#). File paths have no equivalent, andPath.Combinecan misinterpret them. - Encoding: URLs often need special characters encoded (a space as
%20, for example).Path.Combinedoes not do this.
Combining URLs with the Uri class
Be careful with the trailing slash. new Uri(baseUri, relative) resolves the relative part the way a browser resolves a link, so if the base does not end in /, its last segment is replaced, which is why folder is dropped above. Write the base as http://example.com/folder/ to get http://example.com/folder/file.txt.
Concatenating manually
Trim the trailing slash from the base and add exactly one:
Path.Combine vs. Uri
| Feature | Path.Combine | Uri Class/Manual Handling |
| Ease of Use | High for file paths | Moderate for URLs |
| Reliability | High for file paths | High for URLs |
| Correct Separator Handling | OS-dependent | Always correct for URLs |
| Support for URL Components | None | Full support |
| Error-Prone | Low for file paths, High for URLs | Low |
Building URLs safely
Careful encoding and string handling when building URLs also helps prevent security problems such as open redirects and injection attacks.
- Validate URLs, especially when they include user input.
- Use
UriBuilderwhen you need to change individual parts of a URL. - Test URL construction in the different environments you deploy to.
Related reading
- Patterns for Multithreaded Network Server in C
- Pause and Resume Subscription on cold IObservable
- Performance of direct virtual call vs. interface call in C
- Performance of Find vs. FirstOrDefault
- Performance of ReceiveAsync vs. BeginReceive
- Plain Old CLR Object vs Data Transfer Object
- Play audio from a stream using C
- Populating a list of integers in .NET

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.