c# 从字符串中分离文件路径、文件名及扩展名
对文件进行操作时,首先要获取文件路径信息,然后创建文件对象,通过io流将数据读取大宋内存中并进行处理。在操作文件时,可能还需要提取文件的一些信息,比如,文件路径,文件名,扩展名等等,实例如下:
主要用到 打开文件选择对话框,可以选择一个或多个文件,使用需引入命名空间:microsoft.win32,以及对获取的文件路径进行截取substring方法,代码如下
private void btn_select_file_click(object sender, eventargs e) { openfiledialog openfiledialog = new openfiledialog(); if (openfiledialog.showdialog() == dialogresult.ok) { //string filepathall = openfiledialog.filename; string filepathall = "c:\\decktop\\file\\books\\c#学习.exe"; //文件路径 string str_path = filepathall.substring(0, filepathall.lastindexof("\\") + 1); //文件名字 string str_name = filepathall.substring(filepathall.lastindexof("\\") + 1, filepathall.lastindexof(".") - (filepathall.lastindexof("\\") + 1)); //文件扩展名 string str_exc = filepathall.substring(filepathall.lastindexof(".") + 1, filepathall.length - filepathall.lastindexof(".") - 1); //string str_exc = filepathall.split('.')[1].tostring(); // 也可以使用split方法 lbl_file_path.text = "文件路径:" + str_path; lbl_file_name.text = "文件名称:" + str_name; lbl_file_exc.text = "文件扩展时:" + str_exc; } }
indexof()方法与lastindexof()方法的异同:
都是用来查找字符或字符串在指定字符串中的索引,如果未能找到返回-1。不同在于indexof()从指定字符串的前端往后端找到匹配的第一个的索引,lastindexof()从指定字符串的后端往前端找到匹配的第一个的索引。
到此这篇关于c# 从字符串中分离文件路径、文件名及扩展名的文章就介绍到这了,更多相关c# 字符串中分离文件路径内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论