在WinForm窗体应用程序和Web应用程序中,为了上传文件、读取绝对路径下的文件等功能,需要获取文件的物理路径,可以使用以下这些常用方法。
一、在WinForm窗体应用程序中
可用以下方法获取应用程序文件所在文件夹:
System.Environment.CurrentDirectory;
System.IO.Directory.GetCurrentDirectory();
System.Windows.Forms.Application.StartupPath;
System.AppDomain.CurrentDomain.BaseDirectory;
//返回路径末尾有“\”
System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
//返回路径末尾有“\”
System.Threading.Thread.GetDomain().BaseDirectory;
//返回路径末尾有“\”
二、在MVC中
1.在Controller控制器中获取绝对路径:
Server.MapPath("含文件名的虚拟路径");
//返回网站中指定文件的绝对路径
Server.MapPath("/");
//返回网站根目录的绝对路径,末尾有“\”
2.在Models中是无法使用Server.MapPath方法的,这时候可以用以下方法获取网站根目录的绝对路径:
System.AppDomain.CurrentDomain.BaseDirectory;
//返回路径末尾有“\”
System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
//返回路径末尾有“\”
System.Threading.Thread.GetDomain().BaseDirectory;
//返回路径末尾有“\”