C#的一些小知识

时间:2023-03-08 19:43:48
C#的一些小知识

一、Server.MapPath

E:\MyProject\GisSystem\Json\jsonlist.aspx,GisSystem项目下有个Json文件夹,文件夹下有个jsonlist.aspx。
运行jsonlist.aspx时:
Server.MapPath("")//当前运行文件所在的目录,E:\MyProject\GisSystem\Json
Server.MapPath("./")//当前运行文件所在的目录,E:\MyProject\GisSystem\Json\
Server.MapPath("../")//当前运行文件所在目录的父级目录,E:\MyProject\GisSystem\
Server.MapPath("~/")//当前项目所在的根目录,E:\MyProject\GisSystem\

二、System.IO.Path

(1)System.IO.Path.GetDirectoryName(FileName) 返回路经 。
如:GetDirectoryName("c:\test\tmp.txt") 返回 c:\test
(2)System.IO.Path.GetFileName(FileName) 返回不包含路的文件名。
如: GetFileName("c:\test\tmp.txt") 返回 tmp.txt
(3) System.IO.Path.GetExtension(FileName) 返回 后缀名。
如 :GetExtension("c:\test\tmp.txt")返回.txt

三、获取一个文件夹中的指定后缀名文件

 protected  List<string> GetFileFromDic(string filepath, string extension)
{
List<string> pList = new List<string>();
try
{
DirectoryInfo theFolder = new DirectoryInfo(filepath);
FileInfo[] fileInfo = theFolder.GetFiles();
foreach (FileInfo fInfo in fileInfo)
{
if (fInfo.Extension.Contains(extension))
{
pList.Add(fInfo.Name);//包括文件名和扩展名
}
}
}
catch
{
}
return pList;
}