如果我有一个字符串说“abc.txt”,有没有一个快速的方法来获得一个子字符串,这只是“abc”?
我不能做一个fileName.IndexOf('.'),因为文件名可以是“abc.123.txt”或其他东西,我显然只是想摆脱扩展名(即。“abc.123”)。
如果我有一个字符串说“abc.txt”,有没有一个快速的方法来获得一个子字符串,这只是“abc”?
我不能做一个fileName.IndexOf('.'),因为文件名可以是“abc.123.txt”或其他东西,我显然只是想摆脱扩展名(即。“abc.123”)。
当前回答
我知道这是个老问题了,帕西。GetFileNameWithoutExtensionis一个更好的,可能更干净的选项。但就我个人而言,我已经将这两个方法添加到我的项目中,并希望与大家分享。这需要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);
}
其他回答
/// <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!!!");
}
}
框架中有一个用于此目的的方法,该方法将保留除扩展之外的完整路径。
System.IO.Path.ChangeExtension(path, null);
如果只需要文件名,请使用
System.IO.Path.GetFileNameWithoutExtension(path);
的路径。GetFileNameWithoutExtension方法提供了作为参数传递的文件名,但没有扩展名,从名称可以明显看出这一点。
我使用了下面较少的代码
string fileName = "C:\file.docx";
MessageBox.Show(Path.Combine(Path.GetDirectoryName(fileName),Path.GetFileNameWithoutExtension(fileName)));
输出将是
文件C: \