How to convert a relative path to an absolute path in a Windows application?

后端 未结 4 1618
悲&欢浪女
悲&欢浪女 2020-12-02 17:41

How do I convert a relative path to an absolute path in a Windows application?

I know we can use server.MapPath() in ASP.NET. But what can we do in a Windows applica

4条回答
  •  清歌不尽
    2020-12-02 18:35

    It's a bit older topic, but it might be useful for someone. I have solved a similar problem, but in my case, the path was not at the beginning of the text.

    So here is my solution:

    public static class StringExtension
    {
        private const string parentSymbol = "..\\";
        private const string absoluteSymbol = ".\\";
        public static String AbsolutePath(this string relativePath)
        {
            string replacePath = AppDomain.CurrentDomain.BaseDirectory;
            int parentStart = relativePath.IndexOf(parentSymbol);
            int absoluteStart = relativePath.IndexOf(absoluteSymbol);
            if (parentStart >= 0)
            {
                int parentLength = 0;
                while (relativePath.Substring(parentStart + parentLength).Contains(parentSymbol))
                {
                    replacePath = new DirectoryInfo(replacePath).Parent.FullName;
                    parentLength = parentLength + parentSymbol.Length;
                };
                relativePath = relativePath.Replace(relativePath.Substring(parentStart, parentLength), string.Format("{0}\\", replacePath));
            }
            else if (absoluteStart >= 0)
            {
                relativePath = relativePath.Replace(".\\", replacePath);
            }
            return relativePath;
        }
    }
    

    Example:

    Data Source=.\Data\Data.sdf;Persist Security Info=False;
    Data Source=..\..\bin\Debug\Data\Data.sdf;Persist Security Info=False;
    

提交回复
热议问题