কীভাবে পরম পাথ থেকে আপেক্ষিক পথ পাবে


174

আমার অ্যাপ্লিকেশনগুলিতে একটি অংশ রয়েছে যা ওপেনফিলডায়ালগের মাধ্যমে ব্যবহারকারী দ্বারা লোড করা ফাইল পথ প্রদর্শন করে। পুরো পথটি প্রদর্শনের জন্য এটি অনেক বেশি জায়গা নিচ্ছে, তবে আমি কেবল ফাইলের নামটি দ্বিপাক্ষিক হিসাবে প্রদর্শন করতে চাই না। সুতরাং আমি অ্যাসেম্বলি / এক্স ডিরেক্টরি ডিরেক্টরি সম্পর্কিত ফাইলের পথটি প্রদর্শন করতে পছন্দ করব।

উদাহরণস্বরূপ, সমাবেশটি এখানে থাকে C:\Program Files\Dummy Folder\MyProgramএবং তখন ফাইলটি C:\Program Files\Dummy Folder\MyProgram\Data\datafile1.datআমি এটি প্রদর্শন করতে চাই .\Data\datafile1.dat। যদি ফাইলটি থাকে C:\Program Files\Dummy Folder\datafile1.datতবে আমি চাই ..\datafile1.dat। তবে যদি ফাইলটি মূল ডিরেক্টরিতে বা মূলের নীচে 1 ডিরেক্টরিতে থাকে তবে পুরো পথটি প্রদর্শন করুন।

আপনি কি সমাধানের সুপারিশ করবেন? Regex?

মূলত আমি খুব বেশি পর্দার জায়গা না নিয়ে দরকারী ফাইল পাথের তথ্য প্রদর্শন করতে চাই।

সম্পাদনা: আরও কিছুটা স্পষ্ট করার জন্য। এই সমাধানটির উদ্দেশ্য হ'ল ব্যবহারকারীর বা আমার জানার জন্য আমি কোন ফাইলটি সর্বশেষে লোড করেছি এবং কোনটি ডিরেক্টরি থেকে এসেছে তা মোটামুটি জানি। আমি পথটি প্রদর্শনের জন্য একটি পঠনযোগ্য পাঠ্যবক্স ব্যবহার করছি। বেশিরভাগ সময়, ফাইল পাথ পাঠ্যবাক্সের প্রদর্শন স্পেসের তুলনায় অনেক দীর্ঘ। পথটি তথ্যবহুল বলে মনে করা হচ্ছে তবে বেশি স্ক্রিনের জায়গা নেওয়ার পক্ষে এটি যথেষ্ট গুরুত্বপূর্ণ নয়।

অ্যালেক্স ব্রোল্ট মন্তব্যটি ভাল ছিল, জোনাথন লেফলারও তাই। ডেভিডকে প্রদত্ত উইন 32 ফাংশনটি সমস্যার পুরো অংশকেই কেবল সহায়তা করে, তবে যাইহোক ধন্যবাদ। জেমস নিউটন-কিং সলিউশন হিসাবে, আমি যখন মুক্তি পাব পরে এটিকে চেষ্টা করে দেখব।


2
এছাড়াও দেখুন স্ট্যাকওভারফ্লো.com
— সিএডি

উত্তর:


192

.NET কোর 2.0 এ Path.GetRelativePathঅন্যটি ব্যবহার করুন।

/// <summary>
/// Creates a relative path from one file or folder to another.
/// </summary>
/// <param name="fromPath">Contains the directory that defines the start of the relative path.</param>
/// <param name="toPath">Contains the path that defines the endpoint of the relative path.</param>
/// <returns>The relative path from the start directory to the end path or <c>toPath</c> if the paths are not related.</returns>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="UriFormatException"></exception>
/// <exception cref="InvalidOperationException"></exception>
public static String MakeRelativePath(String fromPath, String toPath)
{
    if (String.IsNullOrEmpty(fromPath)) throw new ArgumentNullException("fromPath");
    if (String.IsNullOrEmpty(toPath))   throw new ArgumentNullException("toPath");

    Uri fromUri = new Uri(fromPath);
    Uri toUri = new Uri(toPath);

    if (fromUri.Scheme != toUri.Scheme) { return toPath; } // path can't be made relative.

    Uri relativeUri = fromUri.MakeRelativeUri(toUri);
    String relativePath = Uri.UnescapeDataString(relativeUri.ToString());

    if (toUri.Scheme.Equals("file", StringComparison.InvariantCultureIgnoreCase))
    {
        relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
    }

    return relativePath;
}

32
প্রচুর পরীক্ষার পরেও এই পদ্ধতিটি আমার পক্ষে সবচেয়ে ভাল কাজ করেছে। আপনার মনে রাখতে হবে যে উরি একটি ফোল্ডারটি আচরণ করে যা কোনও পাথ বিভাজক দ্বারা ফাইল হিসাবে শেষ হয় না (বারটি ফোল্ডার হলে সি: oo foo \ বারের পরিবর্তে সি: \ foo \ বার use ব্যবহার করুন)।
— ভিভিএস

6
স্ল্যাশ সমস্যার জন্য সাধারণ সমাধানটি হ'লreturn relativeUri.ToString().Replace('/',Path.DirectorySeparatorChar);
— নাইয়ারগডস

4
একটি বৈধ পথ পাওয়ার জন্য আপনার আপেক্ষিক ইউরি এইভাবে তৈরি করা উচিত; .ToString () উপস্থাপনে এস্কেপ সিকোয়েন্স অন্তর্ভুক্ত করা হবে যা বৈধ নয় এবং পথে প্রয়োজনীয় নয়।
— ইমন নেরবোন

3
আরগ চেকের পরে নীচে যুক্ত করা হয়েছে যদি (fromPath.Last ()! = Path.DirectorySeparatorChar) {from + पथ + = পথ।ডাইরেক্টরিসপেটরচর; } if (toPath.Last ()! = Path.DirectorySeparatorChar) {toPath + = Path.DirectorySeparatorChar; }
— সাইমন

8
আমার জন্য এটি আপেক্ষিক পথে ফিরছে না । কারণ c:\testএবং c:\test\abc.txtএটি ফিরে আসে test\abc.txtযা আমার মতে আপেক্ষিক নয়। আমি ন্যায়বিচারটি আশা করবabc.txt
— 14 জুলাইতে জুয়ারজেন ডি

51

প্রশ্নটি থেকে একটু দেরীতে, তবে আমার পাশাপাশি এই বৈশিষ্ট্যটিও প্রয়োজন needed আমি ডেভিডকে সাথে একমত যেহেতু একটি আছে বিল্ট-ইন এপিআই ফাংশন এটি সরবরাহ করে তাই আপনার এটি ব্যবহার করা উচিত। এটির জন্য একটি পরিচালিত মোড়ক এখানে দেওয়া হয়েছে:

public static string GetRelativePath(string fromPath, string toPath)
{
    int fromAttr = GetPathAttribute(fromPath);
    int toAttr = GetPathAttribute(toPath);

    StringBuilder path = new StringBuilder(260); // MAX_PATH
    if(PathRelativePathTo(
        path,
        fromPath,
        fromAttr,
        toPath,
        toAttr) == 0)
    {
        throw new ArgumentException("Paths must have a common prefix");
    }
    return path.ToString();
}

private static int GetPathAttribute(string path)
{
    DirectoryInfo di = new DirectoryInfo(path);
    if (di.Exists)
    {
        return FILE_ATTRIBUTE_DIRECTORY;
    }

    FileInfo fi = new FileInfo(path);
    if(fi.Exists)
    {
        return FILE_ATTRIBUTE_NORMAL;
    }

    throw new FileNotFoundException();
}

private const int FILE_ATTRIBUTE_DIRECTORY = 0x10;
private const int FILE_ATTRIBUTE_NORMAL = 0x80;

[DllImport("shlwapi.dll", SetLastError = true)]
private static extern int PathRelativePathTo(StringBuilder pszPath, 
    string pszFrom, int dwAttrFrom, string pszTo, int dwAttrTo);

4
যদি ফাইল বা পাথের অস্তিত্ব না থাকে তবে আমি এটি ব্যতিক্রম করব না কারণ এটি সম্পূর্ণ আইনি মামলা হতে পারে।
— ভিভিএস

2
তাহলে গেটপ্যাটঅ্যাট্রিবিউটগুলি কী ফিরে আসবে? "ফাইলের অস্তিত্ব নেই" এর জন্য কোনও পতাকা নেই তাই আমি নিক্ষেপ করা ছাড়া অন্য কোনও কার্যকর বিকল্প দেখতে পাচ্ছি না অন্যথায় কলকারী ভুল তথ্য পেয়ে যায়।
— সিটিচকে

2
মনে রাখবেন যে প্যাথরিলিটিভপথটি মিথ্যা ফিরিয়ে দেয় যদি কোনও আপেক্ষিক পথ তৈরি করা না যায়। সেক্ষেত্রে আপনার হয় স্ট্রিং ফিরে আসা উচিত mp
— ড্যানিয়েল রোজ

4
আমি এটি আরও স্পষ্ট মনে করি: এটি বুল সাফল্য = পাথরেলিটিপ্যাথটো (...) এর মতো কোডকে মঞ্জুরি দেয় যা কোন প্রান্তের চেয়ে আপনাকে বুঝতে সহজ লাগে যেখানে অন্তর্নিহিতটির অর্থ কী তা আপনাকে ডকুমেন্টেশন পড়তে হবে।
— ড্যানিয়েল রোজ

4
লোকেরা ... আপনি কেবল পুরো গেটপ্যাথঅ্যাট্রিবিউটটি সরাতে পারবেন , আপনি জানেন। যতক্ষণ আপনি নিখুঁতভাবে নিশ্চিত করেন যে আপনার দেওয়া আর্গুমেন্টগুলি ডিরেক্টরিগুলি রয়েছে, আপনার কেবল এটি 0x10 দেওয়া দরকার এবং এটি সম্পূর্ণ অস্তিত্বহীন পাথের সাথে কাজ করবে। এবং আমার ক্ষেত্রে, পছন্দসই সমাধানটি কেবল ব্যতিক্রমটি ছুঁড়ে ফেলার পরিবর্তে সম্পূর্ণ পরম টার্গেট পাথ ফিরে ফেলা।
— নায়ারগডস

31

.NET কোর 2.0 উত্তর

.NET কোর ২.০ এ রয়েছে পথ।গেটরেলটিপথ যা এর মতো ব্যবহার করা যেতে পারে:

var relativePath = Path.GetRelativePath(
    @"C:\Program Files\Dummy Folder\MyProgram",
    @"C:\Program Files\Dummy Folder\MyProgram\Data\datafile1.dat");

উপরের উদাহরণে, relativePathভেরিয়েবল সমান Data\datafile1.dat।

বিকল্প। নেট উত্তর

@ ডেভের সমাধান কাজ করে না যখন ফাইল পাথগুলি ফরোয়ার্ড স্ল্যাশ অক্ষর ( /) দিয়ে শেষ হয় না যা পাথটি যদি ডিরেক্টরি পাথ হয় can আমার সমাধান সেই সমস্যাটিকে সংশোধন করে এবং Uri.UriSchemeFileহার্ড কোডিংয়ের পরিবর্তে ধ্রুবকটি ব্যবহার করে "FILE"।

/// <summary>
/// Creates a relative path from one file or folder to another.
/// </summary>
/// <param name="fromPath">Contains the directory that defines the start of the relative path.</param>
/// <param name="toPath">Contains the path that defines the endpoint of the relative path.</param>
/// <returns>The relative path from the start directory to the end path.</returns>
/// <exception cref="ArgumentNullException"><paramref name="fromPath"/> or <paramref name="toPath"/> is <c>null</c>.</exception>
/// <exception cref="UriFormatException"></exception>
/// <exception cref="InvalidOperationException"></exception>
public static string GetRelativePath(string fromPath, string toPath)
{
    if (string.IsNullOrEmpty(fromPath))
    {
        throw new ArgumentNullException("fromPath");
    }

    if (string.IsNullOrEmpty(toPath))
    {
        throw new ArgumentNullException("toPath");
    }

    Uri fromUri = new Uri(AppendDirectorySeparatorChar(fromPath));
    Uri toUri = new Uri(AppendDirectorySeparatorChar(toPath));

    if (fromUri.Scheme != toUri.Scheme)
    {
        return toPath;
    }

    Uri relativeUri = fromUri.MakeRelativeUri(toUri);
    string relativePath = Uri.UnescapeDataString(relativeUri.ToString());

    if (string.Equals(toUri.Scheme, Uri.UriSchemeFile, StringComparison.OrdinalIgnoreCase))
    {
        relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
    }

    return relativePath;
}

private static string AppendDirectorySeparatorChar(string path)
{
    // Append a slash only if the path is a directory and does not have a slash.
    if (!Path.HasExtension(path) &&
        !path.EndsWith(Path.DirectorySeparatorChar.ToString()))
    {
        return path + Path.DirectorySeparatorChar;
    }

    return path;
}

উইন্ডোজ ইন্টারপ উত্তর

PathRelativePathToA নামে একটি উইন্ডোজ এপিআই রয়েছে যা আপেক্ষিক পথটি খুঁজে পেতে ব্যবহার করা যেতে পারে। দয়া করে নোট করুন যে ফাংশনে আপনি যে ফাইল বা ডিরেক্টরি পাথগুলি পাস করেছেন সেগুলি কাজ করার জন্য অবশ্যই এটি উপস্থিত থাকতে হবে।

var relativePath = PathExtended.GetRelativePath(
    @"C:\Program Files\Dummy Folder\MyProgram",
    @"C:\Program Files\Dummy Folder\MyProgram\Data\datafile1.dat");

public static class PathExtended
{
    private const int FILE_ATTRIBUTE_DIRECTORY = 0x10;
    private const int FILE_ATTRIBUTE_NORMAL = 0x80;
    private const int MaximumPath = 260;

    public static string GetRelativePath(string fromPath, string toPath)
    {
        var fromAttribute = GetPathAttribute(fromPath);
        var toAttribute = GetPathAttribute(toPath);

        var stringBuilder = new StringBuilder(MaximumPath);
        if (PathRelativePathTo(
            stringBuilder,
            fromPath,
            fromAttribute,
            toPath,
            toAttribute) == 0)
        {
            throw new ArgumentException("Paths must have a common prefix.");
        }

        return stringBuilder.ToString();
    }

    private static int GetPathAttribute(string path)
    {
        var directory = new DirectoryInfo(path);
        if (directory.Exists)
        {
            return FILE_ATTRIBUTE_DIRECTORY;
        }

        var file = new FileInfo(path);
        if (file.Exists)
        {
            return FILE_ATTRIBUTE_NORMAL;
        }

        throw new FileNotFoundException(
            "A file or directory with the specified path was not found.",
            path);
    }

    [DllImport("shlwapi.dll", SetLastError = true)]
    private static extern int PathRelativePathTo(
        StringBuilder pszPath,
        string pszFrom,
        int dwAttrFrom,
        string pszTo,
        int dwAttrTo);
}

1
যেটি প্রত্যাশা করবে তার মতো অনেক বেশি কাজ করে - আমি সর্বোচ্চ-উত্তোলিত উত্তরের পরিবর্তে এটির প্রস্তাব দিই।
— দ্য মায়ার

আপনি অনুমান হিসাবে দেখা AltDirectorySeparatorCharএকটি সম্ভাবনা, AppendDirectorySeparatorCharএটিও কি পরীক্ষা করা উচিত নয় ?
— ওহাদ স্নাইডার

এছাড়াও, কোনও ফাইল কোনও এক্সটেনশন ছাড়াই হতে পারে, সুতরাং এটি বেশিরভাগ ক্ষেত্রে এটি আরও সুবিধাজনক হতে পারে, এটি আপনাকে কেসটি নির্দিষ্ট করার অনুমতি দেয় না। ফাইল সিস্টেমের এন্ট্রি উপস্থিত রয়েছে কিনা এবং এটি ফাইল বা ফোল্ডার কিনা তা পরীক্ষা করে দেখুন। যদি এটি বিদ্যমান না থাকে তবে এই যুক্তি দিয়ে থাকুন stay অথবা হয়ত ফাইল বা ডিরেক্টরি সরবরাহ করা হয়েছে (যেমন 2 বুলিয়ান) নির্দিষ্ট করে দেওয়ার জন্য স্বাক্ষরটিতে কিছু উপায় যুক্ত করুন।
— ওহাদ স্নাইডার

শেষ পর্যন্ত, আমি স্কিমগুলি পৃথক হলে একটি ব্যতিক্রম ছুঁড়ে দেব।
— ওহাদ স্নাইডার

25

Shlwapi.dll এ একটি উইন 32 (সি ++) ফাংশন রয়েছে যা আপনি যা চান ঠিক তা করে: PathRelativePathTo()

আমি এটি পি / ইনভোক করা ছাড়া। নেট থেকে অন্য কোনও প্রবেশাধিকার সম্পর্কে সচেতন নই।


3
এটি কোন অংশটি সাহায্য করে না? মূল পোস্টটি পড়লে এটি আমার কাছে প্যাথর্লেটিভপ্যাথটো () যেমনটি চেয়েছিল তেমনটি দেখে মনে হচ্ছে তবে এটি সম্ভবত আমি ভুল কিছু দিয়েছি ...
— ডেভিডকে

3
নির্দোষভাবে কাজ করে। পি / ইনভোক কীভাবে সেটআপ করবেন সে সম্পর্কে পিনভোক.নেট / ডিফল্ট.এএসপিএক্স / শ্লাওয়াপি.পথ রিলেটিভপ্যাথটি দেখুন ।
— joce

2
ধন্যবাদ! আমি আসলে একটি সি ++ সমাধান খুঁজছিলাম!
— এনটিডিএলএস

2
এটি লক্ষণীয় যে এখানে ফাংশনগুলি shlwapi.dllএখন এমএসডিএন.ইমক্রোসফটকম "These functions are available through Windows XP Service Pack 2 (SP2) and Windows Server 2003. They might be altered or unavailable in subsequent versions of Windows."
— বেসিক

4
Shlwapi.dll নিজেই হ্রাস করা হয়েছে উল্লেখ করে আমি এই পৃষ্ঠাটি পড়িনি: কেবলমাত্র এটিই বলেছে যে পৃষ্ঠায় তালিকাভুক্ত shlwapi.dll থেকে মোড়কের কাজগুলি অবচিত করা হয়েছে। PathRelativePathTo () নিজেই সেই পৃষ্ঠায় উল্লেখ করা হয়নি, এবং PathRelativePathTo () এর মূল ডকুমেন্টেশন হ্রাসের কোনও উল্লেখ করে না, তাই যতদূর আমি দেখতে পাচ্ছি এটি কল করার জন্য এখনও একটি বৈধ ফাংশন।
— ডেভিডকে

14

যদি আপনি .NET কোর 2.0Path.GetRelativePath() ব্যবহার করেন তবে এই নির্দিষ্ট কার্যকারিতা সরবরাহ করে:

        var relativeTo = @"C:\Program Files\Dummy Folder\MyProgram";
        var path = @"C:\Program Files\Dummy Folder\MyProgram\Data\datafile1.dat";

        string relativePath = System.IO.Path.GetRelativePath(relativeTo, path);

        System.Console.WriteLine(relativePath);
        // output --> Data\datafile1.dat 

অন্যথায়, নেট নেট ফ্রেমওয়ার্কের জন্য (v4.7 হিসাবে) অন্য প্রস্তাবিত উত্তরগুলির মধ্যে একটি ব্যবহার করার পরামর্শ দেয়।


9

আমি অতীতে এটি ব্যবহার করেছি

/// <summary>
/// Creates a relative path from one file
/// or folder to another.
/// </summary>
/// <param name="fromDirectory">
/// Contains the directory that defines the
/// start of the relative path.
/// </param>
/// <param name="toPath">
/// Contains the path that defines the
/// endpoint of the relative path.
/// </param>
/// <returns>
/// The relative path from the start
/// directory to the end path.
/// </returns>
/// <exception cref="ArgumentNullException"></exception>
public static string MakeRelative(string fromDirectory, string toPath)
{
  if (fromDirectory == null)
    throw new ArgumentNullException("fromDirectory");

  if (toPath == null)
    throw new ArgumentNullException("toPath");

  bool isRooted = (Path.IsPathRooted(fromDirectory) && Path.IsPathRooted(toPath));

  if (isRooted)
  {
    bool isDifferentRoot = (string.Compare(Path.GetPathRoot(fromDirectory), Path.GetPathRoot(toPath), true) != 0);

    if (isDifferentRoot)
      return toPath;
  }

  List<string> relativePath = new List<string>();
  string[] fromDirectories = fromDirectory.Split(Path.DirectorySeparatorChar);

  string[] toDirectories = toPath.Split(Path.DirectorySeparatorChar);

  int length = Math.Min(fromDirectories.Length, toDirectories.Length);

  int lastCommonRoot = -1;

  // find common root
  for (int x = 0; x < length; x++)
  {
    if (string.Compare(fromDirectories[x], toDirectories[x], true) != 0)
      break;

    lastCommonRoot = x;
  }

  if (lastCommonRoot == -1)
    return toPath;

  // add relative folders in from path
  for (int x = lastCommonRoot + 1; x < fromDirectories.Length; x++)
  {
    if (fromDirectories[x].Length > 0)
      relativePath.Add("..");
  }

  // add to folders to path
  for (int x = lastCommonRoot + 1; x < toDirectories.Length; x++)
  {
    relativePath.Add(toDirectories[x]);
  }

  // create relative path
  string[] relativeParts = new string[relativePath.Count];
  relativePath.CopyTo(relativeParts, 0);

  string newPath = string.Join(Path.DirectorySeparatorChar.ToString(), relativeParts);

  return newPath;
}

1
আমি এটি খতিয়ে দেখব, এটি পরীক্ষা করার জন্য আমার কিছু সময় প্রয়োজন। ধন্যবাদ
— ত্রুটিযুক্ত

1
আমি সাথী বিটগুলির সাথে দুটি পাথের সাফল্যের সাথে তুলনা করতে পাথ.গেটফুলপাথ () ব্যবহার করার পরামর্শ দেব। উদাহরণ: সি: \ এ \ .. \ বি বনাম সি: vs বি বনাম সি: \ বি \। \
— ভিভিএস

5

অ্যালেক্স ব্রোল্ট যেমন উল্লেখ করেছেন, বিশেষত উইন্ডোজে, পরম পথটি (ড্রাইভ লেটার এবং সমস্ত সহ) দ্ব্যর্থহীন এবং প্রায়শই ভাল।

আপনার ওপেনফায়ালডায়লগটি কি নিয়মিত ট্রি-ব্রাউজার কাঠামো ব্যবহার করা উচিত নয়?

জায়গায় কিছু নামকরণের জন্য, রেফডির একটি ডিরেক্টরি যা আপনি পাথ নির্দিষ্ট করতে চান তার সাথে সম্পর্কিত; AbsName পথটি নাম আপনি মানচিত্রে করতে চান; এবং রিলপথ হ'ল ফলস্বরূপ আপেক্ষিক পথ।

মেলে এই বিকল্পগুলির মধ্যে প্রথমটি নিন:

  • আপনার যদি ড্রাইভের আলাদা আলাদা অক্ষর থাকে তবে রেফডির থেকে অ্যাবসনেমের কোনও আপেক্ষিক পথ নেই; আপনাকে অবশ্যই AbsName ব্যবহার করতে হবে।
  • যদি অ্যাবসনাম রেফডিরের একটি সাব-ডিরেক্টরিতে থাকে বা রেফডিরের মধ্যে একটি ফাইল হয় তবে কেবল রিলপ্যাট তৈরি করতে অ্যাবসনেমের শুরু থেকে রেফারডির সরান; .চ্ছিকভাবে "./" (বা "। \" যেহেতু আপনি উইন্ডোজ থেকে আছেন) প্রিপেন্ড করুন।
  • রেফডির এবং অ্যাবসনামের দীর্ঘতম সাধারণ উপসর্গটি সন্ধান করুন (যেখানে ডি: c অ্যাবসি \ ডিফ এবং ডি: c অ্যাবসি \ ডিফল্ট ভাগ ডি: \ অ্যাবসি দীর্ঘতম সাধারণ উপসর্গ হিসাবে; এটি নামের উপাদানগুলির ম্যাপিং হতে হবে, একটি সাধারণ দীর্ঘতম সাধারণ নয়) সাবস্ট্রিং); একে এলসিপি বলুন। AbsName এবং RefDir থেকে LCP সরান। (RefDir - LCP) এ থাকা প্রতিটি পাথের উপাদানগুলির জন্য, রিলপথ উত্পাদনের জন্য ".. \" থেকে (AbsName - LCP) প্রিপেন্ড করুন।

শেষ বিধিটি চিত্রিত করার জন্য (যা অবশ্যই সবচেয়ে জটিল) এটি দিয়ে শুরু করুন:

RefDir = D:\Abc\Def\Ghi
AbsName = D:\Abc\Default\Karma\Crucible

তারপর

LCP = D:\Abc
(RefDir - LCP) = Def\Ghi
(Absname - LCP) = Default\Karma\Crucible
RelPath = ..\..\Default\Karma\Crucible

আমি টাইপ করার সময়, ডেভিডকে একটি উত্তর তৈরি করেছিল যা আপনাকে বোঝায় যে এই বৈশিষ্ট্যটি আপনার প্রথম প্রয়োজন নয় এবং এই কাজটি করার জন্য একটি স্ট্যান্ডার্ড ফাংশন রয়েছে। এটা ব্যবহার করো. তবে প্রথম নীতিগুলি থেকে আপনার উপায়টি ভাবতে সক্ষম হওয়ার কোনও ক্ষতি নেই।

ইউনিক্স সিস্টেমগুলি ড্রাইভ চিঠিগুলিকে সমর্থন করে না (সুতরাং সবকিছু সর্বদা একই মূল ডিরেক্টরিতে থাকে এবং প্রথম বুলেট তাই অপ্রাসঙ্গিক), ইউনিক্সে একই কৌশল ব্যবহার করা যেতে পারে।


4

এটি প্রায় দীর্ঘ পথ, তবে System.Uri বর্গের MakeRelativeUri নামে একটি পদ্ধতি রয়েছে। আপনি এটি ব্যবহার করতে পারে। সিস্টেম.আইও.প্যাথের কাছে এটি নেই এটি সত্যিই লজ্জার বিষয়।


4

উপরে উল্লিখিত হিসাবে। নেট কোর 2.x এর প্রয়োগ রয়েছে Path.GetRelativePath।

নীচের কোডটি উত্স থেকে অভিযোজিত এবং নেট 4.7.1 ফ্রেমওয়ার্কের সাথে সূক্ষ্মভাবে কাজ করে।

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

//Adapted from https://github.com/dotnet/corefx/blob/master/src/Common/src/CoreLib/System/IO/Path.cs#L697
// by Anton Krouglov

using System.Runtime.CompilerServices;
using System.Diagnostics;
using System.Text;
using Xunit;

namespace System.IO {
    // Provides methods for processing file system strings in a cross-platform manner.
    // Most of the methods don't do a complete parsing (such as examining a UNC hostname), 
    // but they will handle most string operations.
    public static class PathNetCore {

        /// <summary>
        /// Create a relative path from one path to another. Paths will be resolved before calculating the difference.
        /// Default path comparison for the active platform will be used (OrdinalIgnoreCase for Windows or Mac, Ordinal for Unix).
        /// </summary>
        /// <param name="relativeTo">The source path the output should be relative to. This path is always considered to be a directory.</param>
        /// <param name="path">The destination path.</param>
        /// <returns>The relative path or <paramref name="path"/> if the paths don't share the same root.</returns>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="relativeTo"/> or <paramref name="path"/> is <c>null</c> or an empty string.</exception>
        public static string GetRelativePath(string relativeTo, string path) {
            return GetRelativePath(relativeTo, path, StringComparison);
        }

        private static string GetRelativePath(string relativeTo, string path, StringComparison comparisonType) {
            if (string.IsNullOrEmpty(relativeTo)) throw new ArgumentNullException(nameof(relativeTo));
            if (string.IsNullOrEmpty(path)) throw new ArgumentNullException(nameof(path));
            Debug.Assert(comparisonType == StringComparison.Ordinal ||
                         comparisonType == StringComparison.OrdinalIgnoreCase);

            relativeTo = Path.GetFullPath(relativeTo);
            path = Path.GetFullPath(path);

            // Need to check if the roots are different- if they are we need to return the "to" path.
            if (!PathInternalNetCore.AreRootsEqual(relativeTo, path, comparisonType))
                return path;

            int commonLength = PathInternalNetCore.GetCommonPathLength(relativeTo, path,
                ignoreCase: comparisonType == StringComparison.OrdinalIgnoreCase);

            // If there is nothing in common they can't share the same root, return the "to" path as is.
            if (commonLength == 0)
                return path;

            // Trailing separators aren't significant for comparison
            int relativeToLength = relativeTo.Length;
            if (PathInternalNetCore.EndsInDirectorySeparator(relativeTo))
                relativeToLength--;

            bool pathEndsInSeparator = PathInternalNetCore.EndsInDirectorySeparator(path);
            int pathLength = path.Length;
            if (pathEndsInSeparator)
                pathLength--;

            // If we have effectively the same path, return "."
            if (relativeToLength == pathLength && commonLength >= relativeToLength) return ".";

            // We have the same root, we need to calculate the difference now using the
            // common Length and Segment count past the length.
            //
            // Some examples:
            //
            //  C:\Foo C:\Bar L3, S1 -> ..\Bar
            //  C:\Foo C:\Foo\Bar L6, S0 -> Bar
            //  C:\Foo\Bar C:\Bar\Bar L3, S2 -> ..\..\Bar\Bar
            //  C:\Foo\Foo C:\Foo\Bar L7, S1 -> ..\Bar

            StringBuilder
                sb = new StringBuilder(); //StringBuilderCache.Acquire(Math.Max(relativeTo.Length, path.Length));

            // Add parent segments for segments past the common on the "from" path
            if (commonLength < relativeToLength) {
                sb.Append("..");

                for (int i = commonLength + 1; i < relativeToLength; i++) {
                    if (PathInternalNetCore.IsDirectorySeparator(relativeTo[i])) {
                        sb.Append(DirectorySeparatorChar);
                        sb.Append("..");
                    }
                }
            }
            else if (PathInternalNetCore.IsDirectorySeparator(path[commonLength])) {
                // No parent segments and we need to eat the initial separator
                //  (C:\Foo C:\Foo\Bar case)
                commonLength++;
            }

            // Now add the rest of the "to" path, adding back the trailing separator
            int differenceLength = pathLength - commonLength;
            if (pathEndsInSeparator)
                differenceLength++;

            if (differenceLength > 0) {
                if (sb.Length > 0) {
                    sb.Append(DirectorySeparatorChar);
                }

                sb.Append(path, commonLength, differenceLength);
            }

            return sb.ToString(); //StringBuilderCache.GetStringAndRelease(sb);
        }

        // Public static readonly variant of the separators. The Path implementation itself is using
        // internal const variant of the separators for better performance.
        public static readonly char DirectorySeparatorChar = PathInternalNetCore.DirectorySeparatorChar;
        public static readonly char AltDirectorySeparatorChar = PathInternalNetCore.AltDirectorySeparatorChar;
        public static readonly char VolumeSeparatorChar = PathInternalNetCore.VolumeSeparatorChar;
        public static readonly char PathSeparator = PathInternalNetCore.PathSeparator;

        /// <summary>Returns a comparison that can be used to compare file and directory names for equality.</summary>
        internal static StringComparison StringComparison => StringComparison.OrdinalIgnoreCase;
    }

    /// <summary>Contains internal path helpers that are shared between many projects.</summary>
    internal static class PathInternalNetCore {
        internal const char DirectorySeparatorChar = '\\';
        internal const char AltDirectorySeparatorChar = '/';
        internal const char VolumeSeparatorChar = ':';
        internal const char PathSeparator = ';';

        internal const string ExtendedDevicePathPrefix = @"\\?\";
        internal const string UncPathPrefix = @"\\";
        internal const string UncDevicePrefixToInsert = @"?\UNC\";
        internal const string UncExtendedPathPrefix = @"\\?\UNC\";
        internal const string DevicePathPrefix = @"\\.\";

        //internal const int MaxShortPath = 260;

        // \\?\, \\.\, \??\
        internal const int DevicePrefixLength = 4;

        /// <summary>
        /// Returns true if the two paths have the same root
        /// </summary>
        internal static bool AreRootsEqual(string first, string second, StringComparison comparisonType) {
            int firstRootLength = GetRootLength(first);
            int secondRootLength = GetRootLength(second);

            return firstRootLength == secondRootLength
                   && string.Compare(
                       strA: first,
                       indexA: 0,
                       strB: second,
                       indexB: 0,
                       length: firstRootLength,
                       comparisonType: comparisonType) == 0;
        }

        /// <summary>
        /// Gets the length of the root of the path (drive, share, etc.).
        /// </summary>
        internal static int GetRootLength(string path) {
            int i = 0;
            int volumeSeparatorLength = 2; // Length to the colon "C:"
            int uncRootLength = 2; // Length to the start of the server name "\\"

            bool extendedSyntax = path.StartsWith(ExtendedDevicePathPrefix);
            bool extendedUncSyntax = path.StartsWith(UncExtendedPathPrefix);
            if (extendedSyntax) {
                // Shift the position we look for the root from to account for the extended prefix
                if (extendedUncSyntax) {
                    // "\\" -> "\\?\UNC\"
                    uncRootLength = UncExtendedPathPrefix.Length;
                }
                else {
                    // "C:" -> "\\?\C:"
                    volumeSeparatorLength += ExtendedDevicePathPrefix.Length;
                }
            }

            if ((!extendedSyntax || extendedUncSyntax) && path.Length > 0 && IsDirectorySeparator(path[0])) {
                // UNC or simple rooted path (e.g. "\foo", NOT "\\?\C:\foo")

                i = 1; //  Drive rooted (\foo) is one character
                if (extendedUncSyntax || (path.Length > 1 && IsDirectorySeparator(path[1]))) {
                    // UNC (\\?\UNC\ or \\), scan past the next two directory separators at most
                    // (e.g. to \\?\UNC\Server\Share or \\Server\Share\)
                    i = uncRootLength;
                    int n = 2; // Maximum separators to skip
                    while (i < path.Length && (!IsDirectorySeparator(path[i]) || --n > 0)) i++;
                }
            }
            else if (path.Length >= volumeSeparatorLength &&
                     path[volumeSeparatorLength - 1] == PathNetCore.VolumeSeparatorChar) {
                // Path is at least longer than where we expect a colon, and has a colon (\\?\A:, A:)
                // If the colon is followed by a directory separator, move past it
                i = volumeSeparatorLength;
                if (path.Length >= volumeSeparatorLength + 1 && IsDirectorySeparator(path[volumeSeparatorLength])) i++;
            }

            return i;
        }

        /// <summary>
        /// True if the given character is a directory separator.
        /// </summary>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        internal static bool IsDirectorySeparator(char c) {
            return c == PathNetCore.DirectorySeparatorChar || c == PathNetCore.AltDirectorySeparatorChar;
        }

        /// <summary>
        /// Get the common path length from the start of the string.
        /// </summary>
        internal static int GetCommonPathLength(string first, string second, bool ignoreCase) {
            int commonChars = EqualStartingCharacterCount(first, second, ignoreCase: ignoreCase);

            // If nothing matches
            if (commonChars == 0)
                return commonChars;

            // Or we're a full string and equal length or match to a separator
            if (commonChars == first.Length
                && (commonChars == second.Length || IsDirectorySeparator(second[commonChars])))
                return commonChars;

            if (commonChars == second.Length && IsDirectorySeparator(first[commonChars]))
                return commonChars;

            // It's possible we matched somewhere in the middle of a segment e.g. C:\Foodie and C:\Foobar.
            while (commonChars > 0 && !IsDirectorySeparator(first[commonChars - 1]))
                commonChars--;

            return commonChars;
        }

        /// <summary>
        /// Gets the count of common characters from the left optionally ignoring case
        /// </summary>
        internal static unsafe int EqualStartingCharacterCount(string first, string second, bool ignoreCase) {
            if (string.IsNullOrEmpty(first) || string.IsNullOrEmpty(second)) return 0;

            int commonChars = 0;

            fixed (char* f = first)
            fixed (char* s = second) {
                char* l = f;
                char* r = s;
                char* leftEnd = l + first.Length;
                char* rightEnd = r + second.Length;

                while (l != leftEnd && r != rightEnd
                                    && (*l == *r || (ignoreCase &&
                                                     char.ToUpperInvariant((*l)) == char.ToUpperInvariant((*r))))) {
                    commonChars++;
                    l++;
                    r++;
                }
            }

            return commonChars;
        }

        /// <summary>
        /// Returns true if the path ends in a directory separator.
        /// </summary>
        internal static bool EndsInDirectorySeparator(string path)
            => path.Length > 0 && IsDirectorySeparator(path[path.Length - 1]);
    }

    /// <summary> Tests for PathNetCore.GetRelativePath </summary>
    public static class GetRelativePathTests {
        [Theory]
        [InlineData(@"C:\", @"C:\", @".")]
        [InlineData(@"C:\a", @"C:\a\", @".")]
        [InlineData(@"C:\A", @"C:\a\", @".")]
        [InlineData(@"C:\a\", @"C:\a", @".")]
        [InlineData(@"C:\", @"C:\b", @"b")]
        [InlineData(@"C:\a", @"C:\b", @"..\b")]
        [InlineData(@"C:\a", @"C:\b\", @"..\b\")]
        [InlineData(@"C:\a\b", @"C:\a", @"..")]
        [InlineData(@"C:\a\b", @"C:\a\", @"..")]
        [InlineData(@"C:\a\b\", @"C:\a", @"..")]
        [InlineData(@"C:\a\b\", @"C:\a\", @"..")]
        [InlineData(@"C:\a\b\c", @"C:\a\b", @"..")]
        [InlineData(@"C:\a\b\c", @"C:\a\b\", @"..")]
        [InlineData(@"C:\a\b\c", @"C:\a", @"..\..")]
        [InlineData(@"C:\a\b\c", @"C:\a\", @"..\..")]
        [InlineData(@"C:\a\b\c\", @"C:\a\b", @"..")]
        [InlineData(@"C:\a\b\c\", @"C:\a\b\", @"..")]
        [InlineData(@"C:\a\b\c\", @"C:\a", @"..\..")]
        [InlineData(@"C:\a\b\c\", @"C:\a\", @"..\..")]
        [InlineData(@"C:\a\", @"C:\b", @"..\b")]
        [InlineData(@"C:\a", @"C:\a\b", @"b")]
        [InlineData(@"C:\a", @"C:\A\b", @"b")]
        [InlineData(@"C:\a", @"C:\b\c", @"..\b\c")]
        [InlineData(@"C:\a\", @"C:\a\b", @"b")]
        [InlineData(@"C:\", @"D:\", @"D:\")]
        [InlineData(@"C:\", @"D:\b", @"D:\b")]
        [InlineData(@"C:\", @"D:\b\", @"D:\b\")]
        [InlineData(@"C:\a", @"D:\b", @"D:\b")]
        [InlineData(@"C:\a\", @"D:\b", @"D:\b")]
        [InlineData(@"C:\ab", @"C:\a", @"..\a")]
        [InlineData(@"C:\a", @"C:\ab", @"..\ab")]
        [InlineData(@"C:\", @"\\LOCALHOST\Share\b", @"\\LOCALHOST\Share\b")]
        [InlineData(@"\\LOCALHOST\Share\a", @"\\LOCALHOST\Share\b", @"..\b")]
        //[PlatformSpecific(TestPlatforms.Windows)]  // Tests Windows-specific paths
        public static void GetRelativePath_Windows(string relativeTo, string path, string expected) {
            string result = PathNetCore.GetRelativePath(relativeTo, path);
            Assert.Equal(expected, result);

            // Check that we get the equivalent path when the result is combined with the sources
            Assert.Equal(
                Path.GetFullPath(path).TrimEnd(Path.DirectorySeparatorChar),
                Path.GetFullPath(Path.Combine(Path.GetFullPath(relativeTo), result))
                    .TrimEnd(Path.DirectorySeparatorChar),
                ignoreCase: true,
                ignoreLineEndingDifferences: false,
                ignoreWhiteSpaceDifferences: false);
        }
    }
}

বাহ, আপনাকে অনেক ধন্যবাদ! এটি নেট ফ্রেমওয়ার্ক 4.6.1 এর সাথে পুরোপুরি কাজ করে। এই উত্তরটি upvated বা এমনকি সমাধান হিসাবে গ্রহণ করা উচিত।
— j00hi

ধন্যবাদ! সামান্য পরিবর্তন সহ এটি নেট ফ্রেমওয়ার্ক 4.5.2
— বাজে

3

আমি এটি ব্যবহার করছি:

public static class StringExtensions
{
  /// <summary>
  /// Creates a relative path from one file or folder to another.
  /// </summary>
  /// <param name="absPath">Absolute path.</param>
  /// <param name="relTo">Directory that defines the start of the relative path.</param> 
  /// <returns>The relative path from the start directory to the end path.</returns>
  public static string MakeRelativePath(this string absPath, string relTo)
  {
      string[] absParts = absPath.Split(Path.DirectorySeparatorChar);
      string[] relParts = relTo.Split(Path.DirectorySeparatorChar);

      // Get the shortest of the two paths
      int len = absParts.Length < relParts.Length
          ? absParts.Length : relParts.Length;

      // Use to determine where in the loop we exited
      int lastCommonRoot = -1;
      int index;

      // Find common root
      for (index = 0; index < len; index++)
      {
          if (absParts[index].Equals(relParts[index], StringComparison.OrdinalIgnoreCase))
              lastCommonRoot = index;
          else 
            break;
      }

      // If we didn't find a common prefix then throw
      if (lastCommonRoot == -1)
          throw new ArgumentException("The path of the two files doesn't have any common base.");

      // Build up the relative path
      var relativePath = new StringBuilder();

      // Add on the ..
      for (index = lastCommonRoot + 1; index < relParts.Length; index++)
      {
        relativePath.Append("..");
        relativePath.Append(Path.DirectorySeparatorChar);
      }

      // Add on the folders
      for (index = lastCommonRoot + 1; index < absParts.Length - 1; index++)
      {
        relativePath.Append(absParts[index]);
        relativePath.Append(Path.DirectorySeparatorChar);
      }
      relativePath.Append(absParts[absParts.Length - 1]);

      return relativePath.ToString();
  }
}

3

ব্যবহার করুন:

RelPath = AbsPath.Replace(ApplicationPath, ".")

সংকীর্ণ মামলার ক্ষেত্রে এটি দুর্দান্তভাবে কাজ করবে! আমি এটি ব্যবহার করতে যাচ্ছি! আমি মনে করি এই অন্যান্য ছেলেরা একটি সাধারণ উদ্দেশ্য ত্রুটি-চেকিং, এজ-কেস-হ্যান্ডলিং সমাধান চায়। তবে আপনার যদি প্রয়োজন হয় তবে এটি অবশ্যই সহজ!
— ড্যানো

আমি ব্যবহার শেষ path.Replace(rootPath.TrimEnd('\\') + "\\", "")।
— কোনার্ড

2

আপনি যদি নিশ্চিত হন যে আপনার পরম পাথ 2 সর্বদা নিরঙ্কুশ পাথের সাথে তুলনামূলকভাবে থাকে তবে পাথ 2 থেকে প্রথম এন অক্ষরগুলি সরিয়ে ফেলুন, যেখানে এন পথ 1 এর দৈর্ঘ্য।


2

আপনি CommonPathএই RelativePathশ্রেণীর পদ্ধতিটি ব্যবহার করতে চান । আপনার যদি সাধারণ পাথটি হয়ে যায়, তবে আপনি যে পথটি প্রদর্শন করতে চান তা ছাড়ুন।

Namespace IO.Path

    Public NotInheritable Class RelativePath

        Private Declare Function PathRelativePathTo Lib "shlwapi" Alias "PathRelativePathToA" ( _
            ByVal pszPath As String, _
            ByVal pszFrom As String, _
            ByVal dwAttrFrom As Integer, _
            ByVal pszTo As String, _
            ByVal dwAttrTo As Integer) As Integer

        Private Declare Function PathCanonicalize Lib "shlwapi" Alias "PathCanonicalizeA" ( _
            ByVal pszBuf As String, _
            ByVal pszPath As String) As Integer

        Private Const FILE_ATTRIBUTE_DIRECTORY As Short = &H10S

        Private Const MAX_PATH As Short = 260

        Private _path As String
        Private _isDirectory As Boolean

#Region " Constructors "

        Public Sub New()

        End Sub

        Public Sub New(ByVal path As String)
            _path = path
        End Sub

        Public Sub New(ByVal path As String, ByVal isDirectory As Boolean)
            _path = path
            _isDirectory = isDirectory
        End Sub

#End Region

        Private Shared Function StripNulls(ByVal value As String) As String
            StripNulls = value
            If (InStr(value, vbNullChar) > 0) Then
                StripNulls = Left(value, InStr(value, vbNullChar) - 1)
            End If
        End Function

        Private Shared Function TrimCurrentDirectory(ByVal path As String) As String
            TrimCurrentDirectory = path
            If Len(path) >= 2 And Left(path, 2) = ".\" Then
                TrimCurrentDirectory = Mid(path, 3)
            End If
        End Function

        ''' <summary>
        ''' 3. conforming to general principles: conforming to accepted principles or standard practice
        ''' </summary>
        Public Shared Function Canonicalize(ByVal path As String) As String
            Dim sPath As String

            sPath = New String(Chr(0), MAX_PATH)

            If PathCanonicalize(sPath, path) = 0 Then
                Canonicalize = vbNullString
            Else
                Canonicalize = StripNulls(sPath)
            End If

        End Function

        ''' <summary>
        ''' Returns the most common path between two paths.
        ''' </summary>
        ''' <remarks>
        ''' <para>returns the path that is common between two paths</para>
        ''' <para>c:\FolderA\FolderB\FolderC</para>
        '''   c:\FolderA\FolderD\FolderE\File.Ext
        ''' 
        '''   results in:
        '''       c:\FolderA\
        ''' </remarks>
        Public Shared Function CommonPath(ByVal path1 As String, ByVal path2 As String) As String
            'returns the path that is common between two paths
            '
            '   c:\FolderA\FolderB\FolderC
            '   c:\FolderA\FolderD\FolderE\File.Ext
            '
            '   results in:
            '       c:\FolderA\

            Dim sResult As String = String.Empty
            Dim iPos1, iPos2 As Integer
            path1 = Canonicalize(path1)
            path2 = Canonicalize(path2)
            Do
                If Left(path1, iPos1) = Left(path2, iPos2) Then
                    sResult = Left(path1, iPos1)
                End If
                iPos1 = InStr(iPos1 + 1, path1, "\")
                iPos2 = InStr(iPos2 + 1, path1, "\")
            Loop While Left(path1, iPos1) = Left(path2, iPos2)

            Return sResult

        End Function

        Public Function CommonPath(ByVal path As String) As String
            Return CommonPath(_path, path)
        End Function

        Public Shared Function RelativePathTo(ByVal source As String, ByVal isSourceDirectory As Boolean, ByVal target As String, ByVal isTargetDirectory As Boolean) As String
            'DEVLIB
            '   05/23/05  1:47PM - Fixed call to PathRelativePathTo, iTargetAttribute is now passed to dwAttrTo instead of IsTargetDirectory.
            '       For Visual Basic 6.0, the fix does not change testing results,
            '           because when the Boolean IsTargetDirectory is converted to the Long dwAttrTo it happens to contain FILE_ATTRIBUTE_DIRECTORY,
            '
            Dim sRelativePath As String
            Dim iSourceAttribute, iTargetAttribute As Integer

            sRelativePath = New String(Chr(0), MAX_PATH)
            source = Canonicalize(source)
            target = Canonicalize(target)

            If isSourceDirectory Then
                iSourceAttribute = FILE_ATTRIBUTE_DIRECTORY
            End If

            If isTargetDirectory Then
                iTargetAttribute = FILE_ATTRIBUTE_DIRECTORY
            End If

            If PathRelativePathTo(sRelativePath, source, iSourceAttribute, target, iTargetAttribute) = 0 Then
                RelativePathTo = vbNullString
            Else
                RelativePathTo = TrimCurrentDirectory(StripNulls(sRelativePath))
            End If

        End Function

        Public Function RelativePath(ByVal target As String) As String
            Return RelativePathTo(_path, _isDirectory, target, False)
        End Function

    End Class

End Namespace

1

আমি আপনার উভয় পাথ ডিরেক্টরি ডিরেক্টরিতে বিভক্ত করতাম। সেখান থেকে, ডাইভারজেন্সের বিন্দুটি সন্ধান করুন এবং আপনি একবার ডিরেক্টরি পাস করার সময় একটি '../' প্রিপেন্ড করে অ্যাসেম্বলি ফোল্ডারে ফিরে আসুন।

তবে মনে রাখবেন, একটি নিখুঁত পথ সর্বত্র কাজ করে এবং সাধারণত কোনও আপেক্ষিকের চেয়ে পড়া সহজ। এটি সম্পূর্ণরূপে প্রয়োজনীয় না হলে আমি ব্যক্তিগতভাবে কোনও ব্যবহারকারীর আপেক্ষিক পথটি দেখাতাম না।


সম্পূর্ণরূপে সম্মত হন - এমন অনেকগুলি দৃষ্টান্ত রয়েছে যেখানে আপেক্ষিক পথটি পুরো পথের নাম হতে পারে যেমন আপনার সাধারণ মূলটি ড্রাইভ ছিল - সি: so - সুতরাং আপনি এখনও এই কেসটি পরিচালনা করতে চান।
— স্টেফবু

1

আপনি যদি জানেন যে টোপথটি ফ্রিপথ দ্বারা রয়েছে তবে আপনি এটিকে সহজ রাখতে পারবেন keep আমি ব্রেভিটি জন্য দাবী ছেড়ে দেব।

public static string MakeRelativePath(string fromPath, string toPath)
{
    // use Path.GetFullPath to canonicalise the paths (deal with multiple directory seperators, etc)
    return Path.GetFullPath(toPath).Substring(Path.GetFullPath(fromPath).Length + 1);
}

2
তারা যদি বিভিন্ন ফোল্ডারে থাকে তবে কী হবে? এটি ".." যুক্ত হয় না। যদি কোনও একটি পাথ ইতিমধ্যে ".." থাকে তবে কী হবে? এটি আপেক্ষিক পথের ভুল স্তরের ফিরে আসবে। যদি ফাইল এ "মাইফোল্ডার" এ থাকে এবং বি ফাইলটি "মাইলঞ্চবক্স" তে থাকে - এই পদ্ধতিটি ডিরেক্টরি বিভাজক চরগুলির সম্পর্কে জানে না, সুতরাং এটি কেবল "লঞ্চবক্স \ ফাইল" সঠিক পথ বলে মনে করবে। এটা ভয়াবহ।
— BrainSlugs83

1

ইউআরআই ব্যবহার করে এমন ফাংশন "প্রায়" আপেক্ষিক পথে ফিরে এসেছে। এটিতে ডিরেক্টরিটি অন্তর্ভুক্ত ছিল যা সরাসরি ফাইলটি অন্তর্ভুক্ত করে যা আপেক্ষিক পথটি আমি পেতে চেয়েছিলাম।

কিছু সময় আগে আমি একটি সাধারণ ফাংশন লিখেছিলাম যা ফোল্ডার বা ফাইলের আপেক্ষিক পথটি ফিরিয়ে দেয় এবং এটি অন্য ড্রাইভে থাকলেও এতে ড্রাইভ লেটারও অন্তর্ভুক্ত রয়েছে।

এক নজর দেখে নাও:

    public static string GetRelativePath(string BasePath, string AbsolutePath)
    {
        char Separator = Path.DirectorySeparatorChar;
        if (string.IsNullOrWhiteSpace(BasePath)) BasePath = Directory.GetCurrentDirectory();
        var ReturnPath = "";
        var CommonPart = "";
        var BasePathFolders = BasePath.Split(Separator);
        var AbsolutePathFolders = AbsolutePath.Split(Separator);
        var i = 0;
        while (i < BasePathFolders.Length & i < AbsolutePathFolders.Length)
        {
            if (BasePathFolders[i].ToLower() == AbsolutePathFolders[i].ToLower())
            {
                CommonPart += BasePathFolders[i] + Separator;
            }
            else
            {
                break;
            }
            i += 1;
        }
        if (CommonPart.Length > 0)
        {
            var parents = BasePath.Substring(CommonPart.Length - 1).Split(Separator);
            foreach (var ParentDir in parents)
            {
                if (!string.IsNullOrEmpty(ParentDir))
                    ReturnPath += ".." + Separator;
            }
        }
        ReturnPath += AbsolutePath.Substring(CommonPart.Length);
        return ReturnPath;
    }

1

আপনার যদি কেবল পঠনযোগ্য পাঠ্য বাক্স থাকে, আপনি কী এটিকে একটি লেবেল তৈরি করে অটোরেলপিসিস = সত্য সেট করতে পারবেন না?

বিকল্প হিসাবে স্বয়ংক্রিয়ভাবে নিজেকে উত্পাদন করার জন্য কোড সহ পোস্ট রয়েছে: (এটি গ্রিডের জন্য এটি করে, পরিবর্তে আপনাকে পাঠ্য বাক্সের জন্য প্রস্থটি দিতে হবে। এটি ঠিক ঠিক নয় কারণ এটি প্রয়োজনের চেয়ে কিছুটা বেশি হ্যাক করে দেয় , এবং আমি খুঁজে পাইনি যেখানে হিসাবটি ভুল আছে তা সন্ধান করতে পারলাম না you আপনি যদি ইচ্ছা করেন তবে ডিরেক্টরিটির প্রথম অংশটি শেষের চেয়ে অপসারণ করে সংশোধন করা যথেষ্ট সহজ হবে।

Private Function AddEllipsisPath(ByVal text As String, ByVal colIndex As Integer, ByVal grid As DataGridView) As String
    'Get the size with the column's width 
    Dim colWidth As Integer = grid.Columns(colIndex).Width

    'Calculate the dimensions of the text with the current font
    Dim textSize As SizeF = MeasureString(text, grid.Font)

    Dim rawText As String = text
    Dim FileNameLen As Integer = text.Length - text.LastIndexOf("\")
    Dim ReplaceWith As String = "\..."

    Do While textSize.Width > colWidth
        ' Trim to make room for the ellipsis
        Dim LastFolder As Integer = rawText.LastIndexOf("\", rawText.Length - FileNameLen - 1)

        If LastFolder < 0 Then
            Exit Do
        End If

        rawText = rawText.Substring(0, LastFolder) + ReplaceWith + rawText.Substring(rawText.Length - FileNameLen)

        If ReplaceWith.Length > 0 Then
            FileNameLen += 4
            ReplaceWith = ""
        End If
        textSize = MeasureString(rawText, grid.Font)
    Loop

    Return rawText
End Function

Private Function MeasureString(ByVal text As String, ByVal fontInfo As Font) As SizeF
    Dim size As SizeF
    Dim emSize As Single = fontInfo.Size
    If emSize = 0 Then emSize = 12

    Dim stringFont As New Font(fontInfo.Name, emSize)

    Dim bmp As New Bitmap(1000, 100)
    Dim g As Graphics = Graphics.FromImage(bmp)

    size = g.MeasureString(text, stringFont)
    g.Dispose()
    Return size
End Function

0
    public static string ToRelativePath(string filePath, string refPath)
    {
        var pathNormalized = Path.GetFullPath(filePath);

        var refNormalized = Path.GetFullPath(refPath);
        refNormalized = refNormalized.TrimEnd('\\', '/');

        if (!pathNormalized.StartsWith(refNormalized))
            throw new ArgumentException();
        var res = pathNormalized.Substring(refNormalized.Length + 1);
        return res;
    }

0

এই কাজ করা উচিত:

private string rel(string path) {
  string[] cwd  = new Regex(@"[\\]").Split(Directory.GetCurrentDirectory());
  string[] fp   = new Regex(@"[\\]").Split(path);

  int common = 0;

  for (int n = 0; n < fp.Length; n++) {
    if (n < cwd.Length && n < fp.Length && cwd[n] == fp[n]) {
      common++;
    }
  }

  if (common > 0) {
    List<string> rp = new List<string>();

    for (int n = 0; n < (cwd.Length - common); n++) {
      rp.Add("..");
    }

    for (int n = common; n < fp.Length; n++) {
      rp.Add(fp[n]);
    }

    return String.Join("/", rp.ToArray());
  } else {
    return String.Join("/", fp);
  }
}

0

উরির সাথে চলার পথে লিনাক্স / ম্যাকোস সিস্টেমে কাজ হয়নি। পথ '/ var / www / root' উরিতে রূপান্তর করা যায় না। আরও সর্বজনীন উপায় - সমস্ত হাত দিয়ে করুন।

public static string MakeRelativePath(string fromPath, string toPath, string sep = "/")
{
    var fromParts = fromPath.Split(new[] { '/', '\\'},
        StringSplitOptions.RemoveEmptyEntries);
    var toParts = toPath.Split(new[] { '/', '\\'},
        StringSplitOptions.RemoveEmptyEntries);

    var matchedParts = fromParts
        .Zip(toParts, (x, y) => string.Compare(x, y, true) == 0)
        .TakeWhile(x => x).Count();

    return string.Join("", Enumerable.Range(0, fromParts.Length - matchedParts)
        .Select(x => ".." + sep)) +
            string.Join(sep, toParts.Skip(matchedParts));
}        

PS: আমি "/" কে पथের পরিবর্তে পৃথককারীের ডিফল্ট মান হিসাবে ব্যবহার করি irect


0

এখানে আমার:

public static string RelativePathTo(this System.IO.DirectoryInfo @this, string to)
{
    var rgFrom = @this.FullName.Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
    var rgTo = to.Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
    var cSame = rgFrom.TakeWhile((p, i) => i < rgTo.Length && string.Equals(p, rgTo[i])).Count();

    return Path.Combine(
        Enumerable.Range(0, rgFrom.Length - cSame)
        .Select(_ => "..")
        .Concat(rgTo.Skip(cSame))
        .ToArray()
    );
}

0

যেমন কিছু সঙ্গে খেলুন:

private String GetRelativePath(Int32 level, String directory, out String errorMessage) {
        if (level < 0 || level > 5) {
            errorMessage = "Find some more smart input data";
            return String.Empty;
        }
        // ==========================
        while (level != 0) {
            directory = Path.GetDirectoryName(directory);
            level -= 1;
        }
        // ==========================
        errorMessage = String.Empty;
        return directory;
    }

এবং এটি পরীক্ষা

[Test]
    public void RelativeDirectoryPathTest() {
        var relativePath =
            GetRelativePath(3, AppDomain.CurrentDomain.BaseDirectory, out var errorMessage);
        Console.WriteLine(relativePath);
        if (String.IsNullOrEmpty(errorMessage) == false) {
            Console.WriteLine(errorMessage);
            Assert.Fail("Can not find relative path");
        }
    }

0

ইন ASP.NET Core 2, আপনি চাইলে আপেক্ষিক পথটি bin\Debug\netcoreapp2.2নিম্নলিখিত সংমিশ্রণটি ব্যবহার করতে পারেন:

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
public class RenderingService : IRenderingService
{

    private readonly IHostingEnvironment _hostingEnvironment;
    public RenderingService(IHostingEnvironment hostingEnvironment)
    {
    _hostingEnvironment = hostingEnvironment;
    }

    public string RelativeAssemblyDirectory()
    {
        var contentRootPath = _hostingEnvironment.ContentRootPath;
        string executingAssemblyDirectoryAbsolutePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
        string executingAssemblyDirectoryRelativePath = System.IO.Path.GetRelativePath(contentRootPath, executingAssemblyDirectoryAbsolutePath);
        return executingAssemblyDirectoryRelativePath;
    }
}
আমাদের সাইট ব্যবহার করে, আপনি স্বীকার করেছেন যে আপনি আমাদের কুকি নীতি এবং গোপনীয়তা নীতিটি পড়েছেন এবং বুঝতে পেরেছেন ।
Licensed under cc by-sa 3.0 with attribution required.