从文件名string中删除文件扩展名

如果我有一个string说"abc.txt" ,是否有一个快速的方法来获取只是"abc"的子string?

我不能做一个fileName.IndexOf('.')因为文件名可能是"abc.123.txt"什么的,我显然只是想摆脱扩展名(即"abc.123" )。

Path.GetFileNameWithoutExtension方法为您提供了作为parameter passing的文件名,没有扩展名,这应该从名称中显而易见。

在这个框架中有一个方法,除了扩展之外,它将保持完整的path。

 System.IO.Path.ChangeExtension(path, null); 

如果只需要文件名,请使用

 System.IO.Path.GetFileNameWithoutExtension(path); 

您可以使用

 string extension = System.IO.Path.GetExtension(filename); 

然后手动删除扩展名:

 string result = filename.Substring(0, filename.Length - extension.Length); 

String.LastIndexOf会工作。

 string fileName= "abc.123.txt"; int fileExtPos = fileName.LastIndexOf("."); if (fileExtPos >= 0 ) fileName= fileName.Substring(0, fileExtPos); 

如果你想创build没有扩展名的完整path,你可以这样做:

 Path.Combine( Path.GetDirectoryName(fullPath), Path.GetFileNameWithoutExtension(fullPath)) 

但我正在寻找更简单的方法来做到这一点。 有人有什么主意吗?

如果你想使用string操作,那么你可以使用函数lastIndexOf()来search字符或子string的最后一次出现。 Java有许多string函数。

我使用了下面的代码

 string fileName = "C:\file.docx"; MessageBox.Show(Path.GetDirectoryName(fileName)+"\\"+Path.GetFileNameWithoutExtension(fileName)); 

//输出将是“C:\ file”

这个实现应该工作。

 string file = "abc.txt"; string fileNoExtension = file.Replace(".txt", ""); 

你可能不会问UWP API。 但是在UWP中, file.DisplayName是没有扩展名的名称。 希望对他人有用。

  /// <summary> /// Get the extension from the given filename /// </summary> /// <param name="fileName">the given filename ie:abc.123.txt</param> /// <returns>the extension ie:txt</returns> public static string GetFileExtension(this string fileName) { string ext = string.Empty; int fileExtPos = fileName.LastIndexOf(".", StringComparison.Ordinal); if (fileExtPos >= 0) ext = fileName.Substring(fileExtPos, fileName.Length - fileExtPos); return ext; } 
  private void btnfilebrowse_Click(object sender, EventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); //dlg.ShowDialog(); dlg.Filter = "CSV files (*.csv)|*.csv|XML files (*.xml)|*.xml"; if (dlg.ShowDialog() == DialogResult.OK) { string fileName; fileName = dlg.FileName; string filecopy; filecopy = dlg.FileName; filecopy = Path.GetFileName(filecopy); string strFilename; strFilename = filecopy; strFilename = strFilename.Substring(0, strFilename.LastIndexOf('.')); //fileName = Path.GetFileName(fileName); txtfilepath.Text = strFilename; string filedest = System.IO.Path.GetFullPath(".\\Excels_Read\\'"+txtfilepath.Text+"'.csv"); // filedest = "C:\\Users\\adm\\Documents\\Visual Studio 2010\\Projects\\ConvertFile\\ConvertFile\\Excels_Read"; FileInfo file = new FileInfo(fileName); file.CopyTo(filedest); // File.Copy(fileName, filedest,true); MessageBox.Show("Import Done!!!"); } }