What is difference between Path and PathString class?
In C#, Path and PathString are completely different types and are used in different contexts.
| Feature | Path | PathString |
| Namespace | System.IO | Microsoft.AspNetCore.Http |
| Type | static class | struct |
| Purpose | Work with file system paths | Work with HTTP URL paths |
| Used in | Desktop apps, console apps, file handling | ASP.NET Core web apps |
| Represents | File/folder paths | URL request path |
| Example | C:\Docs\file.txt | /products/details |
- Path → File and directory path utilities
System.IO.Path contains static methods to manipulate filesystem paths.
Example:
string full = @"C:\Docs\report.pdf";
Console.WriteLine(Path.GetFileName(full)); // report.pdf
Console.WriteLine(Path.GetExtension(full)); // .pdf
Console.WriteLine(Path.GetDirectoryName(full)); // C:\Docs
Console.WriteLine(Path.Combine("C:\\Docs", "a.txt"));
Console.WriteLine(Path.GetFileName(full)); // report.pdf
Console.WriteLine(Path.GetExtension(full)); // .pdf
Console.WriteLine(Path.GetDirectoryName(full)); // C:\Docs
Console.WriteLine(Path.Combine("C:\\Docs", "a.txt"));
Common methods:
- Path.Combine()
- Path.GetFileName()
- Path.GetExtension()
- Path.GetDirectoryName()
- Path.ChangeExtension()
- Path.GetTempPath()
Path itself does not store a path.
- PathString → URL path wrapper for ASP.NET Core
PathString represents the path part of an HTTP request URL.
Example URL:
https://example.com/products/123?sort=asc
Parts:
- Scheme: https
- Host: example.com
- Path: /products/123 ← PathString
- Query: ?sort=asc
Example:
app.Use(async (context, next) =>
{
PathString path = context.Request.Path;
if (path.StartsWithSegments("/api"))
{
Console.WriteLine("API request");
}
await next();
});
{
PathString path = context.Request.Path;
if (path.StartsWithSegments("/api"))
{
Console.WriteLine("API request");
}
await next();
});
Useful methods:
- StartsWithSegments()
- Add()
- FromUriComponent()
- ToUriComponent()
Example:
PathString p1 = "/users";
PathString p2 = "/123";
Console.WriteLine(p1.Add(p2));// /users/123
Console.WriteLine(p1.Add(p2));// /users/123
One important difference
Path.Combine() automatically uses OS separators:
Path.Combine("docs", "file.txt")
// Windows → docs\file.txt
// Linux → docs/file.txt
// Windows → docs\file.txt
// Linux → docs/file.txt
PathString always uses URL style:
new PathString("/docs/file.txt")
So:
- Use Path → when dealing with files and folders
- Use PathString → when dealing with web request URLs
No comments:
Post a Comment