-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathMongoUrlExtensions.cs
49 lines (42 loc) · 1.42 KB
/
MongoUrlExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using System;
using System.Linq;
using MongoDB.Driver;
public static class MongoUrlExtensions
{
public static string ToConnectionString(this MongoUrl mongoUrl)
{
var builder = new UriBuilder
{
Scheme = mongoUrl.Scheme,
Host = mongoUrl.Server.Host,
Port = mongoUrl.Server.Port
};
// Add username and password if present
if (!string.IsNullOrEmpty(mongoUrl.Username) && !string.IsNullOrEmpty(mongoUrl.Password))
{
builder.UserName = Uri.EscapeDataString(mongoUrl.Username);
builder.Password = Uri.EscapeDataString(mongoUrl.Password);
}
// Add database name if present
if (!string.IsNullOrEmpty(mongoUrl.DatabaseName))
{
builder.Path = "/" + mongoUrl.DatabaseName;
}
// Add query parameters
var query = string.Join(
"&",
mongoUrl.QueryString.AllKeys.Select(key =>
$"{Uri.EscapeDataString(key)}={Uri.EscapeDataString(mongoUrl.QueryString[key])}"
)
);
if (!string.IsNullOrEmpty(query))
{
builder.Query = query;
}
return builder.ToString();
}
}
// Example usage:
// var mongoUrl = new MongoUrl("mongodb://user:password@localhost:27017/mydb?authSource=admin");
// string connectionString = mongoUrl.ToConnectionString();
// Console.WriteLine(connectionString);