Skip to content

Commit 2af04d0

Browse files
committed
Added extension method to get URI for fs object
1 parent 6edb318 commit 2af04d0

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

src/DotNext.Tests/IO/FileUriTests.cs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,14 @@ public static void EncodeAsUri(string fileName, string expected)
3737
Equal(expected, uri.LocalPath);
3838
}
3939

40+
[Fact]
41+
public static void GetUriExtension()
42+
{
43+
var fileName = OperatingSystem.IsWindows() ? "C:\\some\\path" : "/some/path";
44+
var uri = new FileInfo(fileName).GetUri();
45+
Equal(fileName, uri.LocalPath);
46+
}
47+
4048
[Theory]
4149
[MemberData(nameof(GetPaths))]
4250
public static void EncodeAsUriChars(string fileName, string expected)

src/DotNext/IO/FileUri.cs

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,12 @@ public static string Encode(ReadOnlySpan<char> fileName, TextEncoderSettings? se
3333
{
3434
if (fileName.IsEmpty)
3535
throw new ArgumentException(ExceptionMessages.FullyQualifiedPathExpected, nameof(fileName));
36-
37-
var encoder = settings is null ? UrlEncoder.Default : UrlEncoder.Create(settings);
36+
37+
return EncodeCore(fileName, settings is null ? UrlEncoder.Default : UrlEncoder.Create(settings));
38+
}
39+
40+
private static string EncodeCore(ReadOnlySpan<char> fileName, UrlEncoder encoder)
41+
{
3842
var maxLength = GetMaxEncodedLengthCore(fileName, encoder);
3943
using var buffer = (uint)maxLength <= (uint)SpanOwner<char>.StackallocThreshold
4044
? stackalloc char[maxLength]
@@ -137,4 +141,17 @@ private static ReadOnlySpan<char> GetPathComponent(ref ReadOnlySpan<char> fileNa
137141

138142
return component;
139143
}
144+
145+
/// <summary>
146+
/// Gets URI that points to the file system object.
147+
/// </summary>
148+
/// <param name="fileInfo">The information about file system object.</param>
149+
/// <param name="settings">The encoding settings.</param>
150+
/// <returns><see cref="Uri"/> that points to the file system object.</returns>
151+
public static Uri GetUri(this FileSystemInfo fileInfo, TextEncoderSettings? settings = null)
152+
{
153+
ArgumentNullException.ThrowIfNull(fileInfo);
154+
155+
return new(EncodeCore(fileInfo.FullName, settings is null ? UrlEncoder.Default : UrlEncoder.Create(settings)), UriKind.Absolute);
156+
}
140157
}

0 commit comments

Comments
 (0)