How to use server.mappath in C#?

In order to use the Server.MapPath method in C#, you need to reference the System.Web namespace so that you can access the Server object.

The Server.MapPath method is used to map a relative path to a physical file system path. Here is an example of using Server.MapPath:

using System;
using System.Web;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // 获取当前应用程序的根目录路径
            string rootPath = HttpContext.Current.Server.MapPath("~");
            Console.WriteLine("Root Path: " + rootPath);

            // 获取相对于当前页面的路径
            string relativePath = HttpContext.Current.Server.MapPath("~/Images");
            Console.WriteLine("Relative Path: " + relativePath);

            // 获取相对于当前页面的路径的物理文件系统路径
            string absolutePath = HttpContext.Current.Server.MapPath("~/Images/image.jpg");
            Console.WriteLine("Absolute Path: " + absolutePath);
        }
    }
}

In the example above, we first obtain the root directory path of the current application, then get the path relative to the current page, and finally acquire the physical file system path relative to the current page.

bannerAds