c# - 如何创建和解析相对路径?

标签 c# file-io path

我的应用程序在执行目录的子目录中打开文件,子目录称为 sample 并且它包含文件:

  • example.raf(示例扩展,无意义)
  • background.gif

example.raf 包含到 background.gif 的相对路径(在这种情况下只有文件名,因为文件与 raf 位于同一目录中)并且打开 RAF 会导致应用程序读取并显示 background.gif

当我使用 OpenFileDialog 加载 RAF 文件时,一切正常,图像加载正确。我知道打开文件对话框以某种方式更改了当前工作目录,但我无法在不调用打开文件对话框的情况下重新创建它

不幸的是,当我直接从代码调用raf reading 方法时,没有像这样提供文件形式OpenFileDialog 的路径

LoadRAF("sample\\example.raf");

在这种情况下,我遇到了问题,应用程序尝试从 ExecutablePath 而不是从包含 RAF 文件和 image 的子目录加载图像。当然,这是正常行为,但在这种情况下,这是非常不受欢迎的。它需要在我的应用程序中处理相对和绝对类型的路径,所以我应该怎么做才能解决这个问题,如何更改 ExecutablePath 或者我可以做些什么来使这项工作至少像在 OpenFileDialog 的情况下?

最佳答案

我的项目 ZipSolution 中的下一个代码 ( http://zipsolution.codeplex.com/ ) 显示如何在 .net 中解析和创建相对路径

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

namespace ZipSolution
{
    internal static class RelativePathDiscovery
    {
        /// <summary>
        /// Produces relative path when possible to go from baseLocation to targetLocation
        /// </summary>
        /// <param name="baseLocation">The root folder</param>
        /// <param name="targetLocation">The target folder</param>
        /// <returns>The relative path relative to baseLocation</returns>
        /// <exception cref="ArgumentNullException">base or target locations are null or empty</exception>
        public static string ProduceRelativePath(string baseLocation, string targetLocation)
        {
            if (string.IsNullOrEmpty(baseLocation))
            {
                throw new ArgumentNullException("baseLocation");
            }

            if (string.IsNullOrEmpty(targetLocation))
            {
                throw new ArgumentNullException("targetLocation");
            }

            if (!Path.IsPathRooted(baseLocation))
            {
                return baseLocation;
            }

            if (!Path.IsPathRooted(targetLocation))
            {
                return targetLocation;
            }

            if (string.Compare(Path.GetPathRoot(baseLocation), Path.GetPathRoot(targetLocation), true) != 0)
            {
                return targetLocation;
            }

            if (string.Compare(baseLocation, targetLocation, true) == 0)
            {
                return ".";
            }

            string resultPath = ".";

            if (!targetLocation.EndsWith(@"\"))
            {
                targetLocation = targetLocation + @"\";
            }

            if (baseLocation.EndsWith(@"\"))
            {
                baseLocation = baseLocation.Substring(0, baseLocation.Length - 1);
            }

            while (!targetLocation.StartsWith(baseLocation + @"\", StringComparison.OrdinalIgnoreCase))
            {
                resultPath = resultPath + @"\..";
                baseLocation = Path.GetDirectoryName(baseLocation);

                if (baseLocation.EndsWith(@"\"))
                {
                    baseLocation = baseLocation.Substring(0, baseLocation.Length - 1);
                }
            }

            resultPath = resultPath + targetLocation.Substring(baseLocation.Length);

            // preprocess .\ case
            return resultPath.Substring(2, resultPath.Length - 3);
        }

        /// <summary>
        /// Resolves the relative pathes
        /// </summary>
        /// <param name="relativePath">Relative path</param>
        /// <param name="basePath">base path for discovering</param>
        /// <returns>Resolved path</returns>
        public static string ResolveRelativePath(string relativePath, string basePath)
        {
            if (string.IsNullOrEmpty(basePath))
            {
                throw new ArgumentNullException("basePath");
            }

            if (string.IsNullOrEmpty(relativePath))
            {
                throw new ArgumentNullException("relativePath");
            }

            var result = basePath;

            if (Path.IsPathRooted(relativePath))
            {
                return relativePath;
            }

            if (relativePath.EndsWith(@"\"))
            {
                relativePath = relativePath.Substring(0, relativePath.Length - 1);
            }

            if (relativePath == ".")
            {
                return basePath;
            }

            if (relativePath.StartsWith(@".\"))
            {
                relativePath = relativePath.Substring(2);
            }

            relativePath = relativePath.Replace(@"\.\", @"\");
            if (!relativePath.EndsWith(@"\"))
            {
                relativePath = relativePath + @"\";
            }

            while (!string.IsNullOrEmpty(relativePath))
            {
                int lengthOfOperation = relativePath.IndexOf(@"\") + 1;
                var operation = relativePath.Substring(0, lengthOfOperation - 1);
                relativePath = relativePath.Remove(0, lengthOfOperation);

                if (operation == @"..")
                {
                    result = Path.GetDirectoryName(result);
                }
                else
                {
                    result = Path.Combine(result, operation);
                }
            }

            return result;
        }
    }
}

关于c# - 如何创建和解析相对路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/164630/

相关文章:

java - OSX 上 Eclipse 中的环境变量

c# - .Net Framework 4.5 中数组的 MaxSize

c# - Razor 页面命名空间与类库冲突

c# - 将 DateTime 反序列化为 WCF SOAP 服务 C# 上的参数的异常

c -/proc 伪文件的打开/关闭策略

file-io - 如何使用 vala 递归复制目录?

php - 使用 PHP 上传多个图像并将条目提交到 mysql

node.js - Node - 检查路径中是否存在命令

C# 使用静态变量作为 DeploymentItem 的参数

c# - 尝试连接到 Windows Azure 服务总线时出现 DNS 错误