管理

文件夹判断操作类 - C#小函数类推荐

Posted on 2024-07-30 09:30  lzhdim  阅读(10259)  评论(0编辑  收藏  举报

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

/***

    文件夹判断操作类

    Austin Liu 刘恒辉
    Project Manager and Software Designer

    E-Mail: lzhdim@163.com
    Blog:   http://lzhdim.cnblogs.com
    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;
        }
    }
}

 

Copyright © 2000-2022 Lzhdim Technology Software All Rights Reserved