文件系列--截取路徑字符串,獲取文件名

現在使用的Word 或Excel都有兩種格式,以Word爲例,".doc" 或者".docx",取Word不帶後綴的文件名涉及到字符串的截取;

    需求是截取Word的文件名,然後換成".pdf的後綴",下面是具體的字符串截取的方式;

1.使用Split 和 Substring組合,截成數組;

/// <summary>
        /// 絕對路徑轉相對路徑
        /// </summary>
        /// <param name="strUrl"></param>
        /// <returns></returns>
        private static string urlConvertor(string strUrl)
        {
            string tmpRootDir = HttpContext.Current.Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString());//獲取程序根目錄
            string urlPath = strUrl.Replace(tmpRootDir, ""); //轉換成相對路徑
            urlPath = urlPath.Replace(@"/", @"/");
            return urlPath;
        }
 
        /// <summary>
        /// 相對路徑轉絕對路徑
        /// </summary>
        /// <param name="strUrl"></param>
        /// <returns></returns>
        private static string urlConvertorLocal(string strUrl)
        {
            string tmpRootDir = HttpContext.Current.Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString());//獲取程序根目錄
            string urlPath = tmpRootDir + strUrl.Replace(@"/", @"/"); //轉換成絕對路徑
            return urlPath;
}

 

2.使用Substring 和 LastIndexOf組合,截取字符串;

下面的這種方式簡單粗暴;
    class Program
    {
        static void Main(string[] args)
        {
            string str = "fxq.5.6.doc";    //文件名稱中設計多個特定符號;
            str = str.Substring(0, str.LastIndexOf("."));
            Console.WriteLine(str);
            Console.Read();
        }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章