Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,641 questions

55,376 answers

573 users

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
...