C#文件下引用Server.MapPath报错,求解!

img

我在网上搜了很多都是说
引using System.Web
或者System.Web.HttpContext.Current.Server.MapPath
但是都没用啊

求大佬解疑

引using System.Web后可以用,下面winform项目都可以用,但是可能会出错,机制不一样。题主是什么项目先?

img

看起来像是 winform,在 winform 项目中,没有 System.Web.HttpContext.Current 进程的,所以不能调用这个 Server.MapPath

我这里有个方法,你可以参考下

        public static string MapPath(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                path = "";
            }
            string result = Regex.Replace(path, @"[/\\]+", "/");
            if (Regex.IsMatch(path, @"^[a-z]:", RegexOptions.IgnoreCase))
            {
                result = Regex.Replace(result, @"[/]", "\\");
            }
            else
            {
                if (System.Web.HttpContext.Current != null)
                {
                    result = System.Web.HttpContext.Current.Server.MapPath(result);
                }
                else if (!string.IsNullOrEmpty(Application.StartupPath))
                {
                    result = Application.StartupPath + result;
                }
                else
                {
                    result = System.Web.HttpRuntime.AppDomainAppPath + result;
                }
            }
            return Regex.Replace(result, @"[\\]+$", "");
        }