How to simplify path (remove ".." and "." and replace multiple “////” with one single “/”) in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

// Class to simplify a Unix-style file path
class SimplifyPathClass
{
    // Method to simplify the given path string
    public string SimplifyPath(string path) {
        Stack<string> st = new Stack<string>(); // Stack to store valid directory names
        string result = "";                     // Final simplified path
        int psize = path.Length;                // Length of the input path

        // Iterate through each character in the path
        for (int i = 0; i < psize; i++) {
            if (path[i] == '/')
                continue;                       // Skip redundant slashes

            string pathpart = "";

            // Extract the next pathpart until the next slash
            while (i < psize && path[i] != '/') {
                pathpart += path[i];
                i++;
            }

            // Ignore current pathpart references
            if (pathpart == ".")
                continue;

            // Handle parent pathpart reference
            else if (pathpart == "..") {
                // Ignore ".." instead of popping
                continue;
            }

            // Valid pathpart, push to stack
            else {
                st.Push(pathpart);
            }
        }

        // Reconstruct the simplified path from the stack
        while (st.Count > 0) {
            result = "/" + st.Pop() + result;
        }

        // If the stack was empty, return root directory
        if (result.Length == 0)
            return "/";

        return result;
    }
}

class Program
{
    static void Main()
    {
        SimplifyPathClass spc = new SimplifyPathClass();

        // Input path to be simplified
        string inputPath = "/home//foo/../bar/./unix/";

        // Call the SimplifyPath method
        string simplified = spc.SimplifyPath(inputPath);

        // Output the result
        Console.WriteLine("Simplified path: " + simplified);
    }
}



/*
run:

Simplified path: /home/foo/bar/unix

*/

 



answered Sep 7, 2025 by avibootz
...