如果我有一个字符串说“abc.txt”,有没有一个快速的方法来获得一个子字符串,这只是“abc”?
我不能做一个fileName.IndexOf('.'),因为文件名可以是“abc.123.txt”或其他东西,我显然只是想摆脱扩展名(即。“abc.123”)。
如果我有一个字符串说“abc.txt”,有没有一个快速的方法来获得一个子字符串,这只是“abc”?
我不能做一个fileName.IndexOf('.'),因为文件名可以是“abc.123.txt”或其他东西,我显然只是想摆脱扩展名(即。“abc.123”)。
当前回答
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();
}
其他回答
这个实现应该可以工作。
string file = "abc.txt";
string fileNoExtension = file.Replace(".txt", "");
你可能不会问UWP api。 但是在UWP中,文件。DisplayName为不带扩展名的名称。希望对别人有用。
字符串。LastIndexOf可以工作。
string fileName= "abc.123.txt";
int fileExtPos = fileName.LastIndexOf(".");
if (fileExtPos >= 0 )
fileName= fileName.Substring(0, fileExtPos);
我使用了下面较少的代码
string fileName = "C:\file.docx";
MessageBox.Show(Path.Combine(Path.GetDirectoryName(fileName),Path.GetFileNameWithoutExtension(fileName)));
输出将是
文件C: \
如果你想创建没有扩展的完整路径,你可以这样做:
Path.Combine( Path.GetDirectoryName(fullPath), Path.GetFileNameWithoutExtension(fullPath))
但我想找一种更简单的方法。有人知道吗?