Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Normalizing file paths

Tags:

.net

c#-2.0

I need to normalize a file path so that a part of the path can be matched via String.StartsWith(...)

Example:

  • FullPath: C:/Common/Dir1/Dir2/file.txt
  • CommonPath: C:\Common\

Although those two file paths are equivalent, the common part can't be matched via the method String.StartsWith(...).

I now that the API method: Path.NormalizePath(path, true); can do the normalization, but unfortunately this method is internal protected!

What other opportunities do I have in order to get the file paths normalized? Path.GetFullPath(...) is probably on option, but only works for absolute file paths since it will add a prefix like: C:/ for relative ones.

like image 692
My-Name-Is Avatar asked Sep 16 '25 01:09

My-Name-Is


1 Answers

this work under .net 2.0

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var path = @"C:/Common/Dir1/Dir2/file.txt";
            var canonicalPath = new Uri(path).LocalPath;

            Console.WriteLine(canonicalPath.StartsWith(@"C:\Common\"));

            Console.Read();
        }
    }
}
like image 78
Fredou Avatar answered Sep 19 '25 16:09

Fredou