此文记录的是关于文件夹操作的小函数。

/***

    文件夹判断操作类

    Austin Liu 刘恒辉
    Project Manager and Software Designer


    Date:   2024-01-15 15:18:00

***/

namespace Lzhdim.LPF.Utility
{
    using System;

    using System.IO;

    /// <summary>
    /// 文件夹判断操作类
    /// </summary>
    public class DirDetermineUtil
    {
        /// <summary>
        /// 判断目录和文件是否在同一个目录下
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="directoryPath">文件夹路径</param>
        /// <returns>true 在同一个文件夹;false 不在同一个文件夹</returns>
        public static bool AreInSameDirectory(string filePath, string directoryPath)
        {
            // 获取文件的目录路径
            string fileDirectory = Path.GetDirectoryName(filePath);

            // 标准化路径,移除尾部的斜杠
            fileDirectory = fileDirectory.TrimEnd(Path.DirectorySeparatorChar);
            directoryPath = directoryPath.TrimEnd(Path.DirectorySeparatorChar);

            // 比较两者是否相等
            return string.Equals(fileDirectory, directoryPath, StringComparison.OrdinalIgnoreCase);
        }

        /// <summary>
        /// 获取文件路径所在的目录名
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>文件所在目录</returns>
        public static string GetFileLocatedDirName(string filePath)
        {
            string fileDir = Path.GetDirectoryName(filePath);

            if (fileDir == null)
            {
                //根目录
                return Path.GetPathRoot(filePath);
            }

            int lastIndex = fileDir.LastIndexOf("\\");

            return fileDir.Substring(lastIndex + 1, fileDir.Length - lastIndex - 1);
        }

        /// <summary>
        /// 判断当前文件是否在根目录
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>true 在根目录;false 不在根目录</returns>
        public static bool IsInLocatedRootDir(string filePath)
        {
            //如果没获取到路径的目录,则为根目录
            return Path.GetDirectoryName(filePath) == null;
        }
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.