現在使用的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(); } }