如果我有一个字符串,比如说"abc.txt"
,有没有一种快速的方式可以得到只包含"abc"
的子串?
我不能使用fileName.IndexOf('.')
,因为文件名可能是"abc.123.txt"
之类的,而我显然只想去掉扩展名(即"abc.123"
)。
Path.GetFileNameWithoutExtension
方法可以将你作为参数传递的文件名返回,但不包括扩展名,正如方法名称所表明的那样。
框架中有一个方法可以实现此目的,它将保留完整的路径,但不包括扩展名。
System.IO.Path.ChangeExtension(path, null);
如果只需要文件名,请使用
System.IO.Path.GetFileNameWithoutExtension(path);
null
具有神奇的意义。如果你使用 String.Empty
或者 ""
,最后会留下一个句点 [.
]。 - THBBFTGetFileNameWithoutExtension
更加明确。虽然了解它的潜在副作用和避免它的替代方法也是很好的。 - jeromej[System.IO.Path]::ChangeExtension($FilePath,$null)
解释为[System.IO.Path]::ChangeExtension($FilePath,'')
或[System.IO.Path]::ChangeExtension($FilePath,[string]::Empty)
。 - Bacon Bits你可以使用
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);
foo/bar.cat/cheese
!请警惕! - CameronString.LastIndexOf
对于类似这样的操作来说是有风险的。对于没有扩展名的文件,就像 @Cameron 上面所说的那样,你得到的结果可能不是你想要的。最安全的方法是使用 @Logman 上面的答案。 - Shiva如果您想创建没有扩展名的完整路径,可以尝试以下方法:
Path.Combine( Path.GetDirectoryName(fullPath), Path.GetFileNameWithoutExtension(fullPath))
但我正在寻找更简单的方法来做到这一点。有人有什么想法吗?
string fileName = "C:\file.docx";
MessageBox.Show(Path.Combine(Path.GetDirectoryName(fileName),Path.GetFileNameWithoutExtension(fileName)));
输出将为
C:\file
Path.Combine()
而不是直接指定"\\"
。 - Broots Waymb您可能不会使用UWP API。但在UWP中,file.DisplayName
是没有扩展名的名称。希望对其他人有用。
ReadOnlySpan<char> filename = "abc.def.ghi.txt";
var fileNameWithoutExtension = RemoveFileExtension(filename); //abc.def.ghi
string RemoveFileExtension(ReadOnlySpan<char> path)
{
var lastPeriod = path.LastIndexOf('.');
return (lastPeriod < 0 ? path : path[..lastPeriod]).ToString();
}
我知道这是一个老问题,而 Path.GetFileNameWithoutExtension
是一个更好的,也许更干净的选项。但就我个人而言,我已经将这两种方法添加到我的项目中并希望分享它们。这需要 C# 8.0,因为它使用范围和索引。
public static string RemoveExtension(this string file) => ReplaceExtension(file, null);
public static string ReplaceExtension(this string file, string extension)
{
var split = file.Split('.');
if (string.IsNullOrEmpty(extension))
return string.Join(".", split[..^1]);
split[^1] = extension;
return string.Join(".", split);
}