[Mono-list] how to get relative path

Charlie Poole charlie at nunit.com
Mon Jan 12 16:21:18 EST 2009


Right, but beware that you have to do some post-processing
on the Codebase return value to get it to work as a
local path, especially if you want it to work on both
Linux and Windows. Here's what I use, in case it's helpful
to anyone:

        public static string GetAssemblyPath(Assembly assembly)
        {
            string path = assembly.CodeBase;
            Uri uri = new Uri(path);

            // If it wasn't loaded locally, use the Location
            if (!uri.IsFile)
                return assembly.Location;

            if (uri.IsUnc)
                return path.Substring(Uri.UriSchemeFile.Length + 1);


            int start = Uri.UriSchemeFile.Length +
Uri.SchemeDelimiter.Length;

            if (path[start] == '/' && path[start + 2] == ':')
                ++start;

            return path.Substring(start);
        }

Charlie

> -----Original Message-----
> From: Andrus [mailto:kobruleht2 at hot.ee] 
> Sent: Monday, January 12, 2009 12:33 PM
> To: Charlie Poole; 'Chris Howie'; 'YyYo'
> Cc: mono-list at lists.ximian.com
> Subject: Re: [Mono-list] Re: how to get relative path
> 
> > This will break if the program is loaded from the shadow copy cache.
> 
> 
> You can use CodeBase instead which works with shadow assemblies also:
> 
> String strAppDir = Path.GetDirectoryName(
>                  Assembly.GetExecutingAssembly().GetName().CodeBase);
> 
> Andrus.
> 





More information about the Mono-list mailing list