Formats the file path as a relative Unix path. - CSharp System.IO

CSharp examples for System.IO:File Path

Description

Formats the file path as a relative Unix path.

Demo Code


using System.Threading.Tasks;
using System.Text;
using System.Linq;
using System.IO;/*from  w  w  w  . jav  a 2 s .  c om*/
using System.Collections.Generic;
using System;
using Parchive.Library.Exceptions;

public class Main{
        /// <summary>
        /// Formats the file path as a relative Unix path.
        /// </summary>
        /// <param name="fi">The FileInfo object.</param>
        /// <param name="di">The base directory.</param>
        /// <returns>A Unix path to the file.</returns>
        /// <exception cref="Parchive.Library.Exceptions.PathError">
        /// The base directory isn't valid for this file.
        /// </exception>
        public static string GetUnixPath(this FileInfo fi, DirectoryInfo di)
        {
            var dir = fi.Directory;

            while (dir != null)
            {
                if (dir.FullName == di.FullName)
                {
                    break;
                }

                dir = dir.Parent;

                if (dir == null)
                {
                    throw new PathError("Invalid base directory");
                }
            }

            return fi.FullName.Replace(dir.FullName, string.Empty).Replace('\\', '/').TrimStart('/');
        }
}

Related Tutorials