C#-এ Uri.MakeRelativeUri(Uri) মেথডটি দুটি URI ইনস্ট্যান্সের মধ্যে পার্থক্য নির্ণয় করে এবং একটি রিলেটিভ URI ফেরত দেয়। এটি বেস URI থেকে টার্গেট URI-তে যাওয়ার পথ দर्शায়।
সিনট্যাক্স (Syntax)
public Uri MakeRelativeUri(Uri uri);
এখানে uri প্যারামিটারটি হলো যে URI-র সাথে বর্তমান URI-র তুলনা করা হবে।
উদাহরণ ১: একই ডোমেনের বিভিন্ন পেজ
using System;
public class Demo
{
public static void Main()
{
Uri newURI1 = new Uri("https://www.tutorialspoint.com/");
Console.WriteLine("URI = " + newURI1);
Uri newURI2 = new Uri("https://www.tutorialspoint.com/java.htm");
Console.WriteLine("URI = " + newURI2);
if (newURI1.Equals(newURI2))
Console.WriteLine("Both the URIs are equal!");
else
Console.WriteLine("Both the URIs aren't equal!");
Uri res = newURI1.MakeRelativeUri(newURI2);
Console.WriteLine("Relative uri = " + res);
}
}
আউটপুট
URI = https://www.tutorialspoint.com/ URI = https://www.tutorialspoint.com/java.htm Both the URIs aren't equal! Relative uri = java.htm
উদাহরণ ২: ফ্র্যাগমেন্ট (Fragment) সহ URI
using System;
public class Demo
{
public static void Main()
{
Uri newURI1 = new Uri("https://www.tutorialspoint.com/");
Console.WriteLine("URI = " + newURI1);
Uri newURI2 = new Uri("https://www.tutorialspoint.com/jquery.htm#abcd");
Console.WriteLine("URI = " + newURI2);
if (newURI1.Equals(newURI2))
Console.WriteLine("Both the URIs are equal!");
else
Console.WriteLine("Both the URIs aren't equal!");
Uri res = newURI1.MakeRelativeUri(newURI2);
Console.WriteLine("Relative uri = " + res);
}
}
আউটপুট
URI = https://www.tutorialspoint.com/ URI = https://www.tutorialspoint.com/jquery.htm#abcd Both the URIs aren't equal! Relative uri = jquery.htm#abcd
গুরুত্বপূর্ণ নোটস
- উভয় URI অবশ্যই একই স্কিম (http/https) এবং হোস্টের হতে হবে, অন্যথায় এটি এক্সেপশন ফেলবে
- ফলাফলটি সবসময় একটি রিলেটিভ URI (UriKind.Relative)
- যদি URI দুটি একই হয়, তবে খালি স্ট্রিং ফেরত দেয়
- এটি
UriKind.RelativeOrAbsoluteসমর্থন করে
এক্সেপশন হ্যান্ডলিং উদাহরণ
using System;
public class Demo
{
public static void Main()
{
try
{
Uri baseUri = new Uri("https://example.com/");
Uri differentHost = new Uri("https://another.com/page");
Uri relative = baseUri.MakeRelativeUri(differentHost);
Console.WriteLine(relative);
}
catch (InvalidOperationException ex)
{
Console.WriteLine("Error: " + ex.Message);
// Output: Error: This operation is not supported for a relative URI.
}
}
}
ব্যবহার ক্ষেত্র: ওয়েব ক্রলিং, সাইটম্যাপ জেনারেশন, রিলেটিভ লিংক তৈরি ইত্যাদিতে এটি খুব উপকারী।