using System;
using System.IO;
public static class FileHelper
{
/// <summary>
/// Removes the last file extension from a filename or path.
/// </summary>
/// <param name="path">
/// The filename or full path.
/// </param>
/// <returns>
/// The filename/path without its last extension.
/// </returns>
/// <exception cref="ArgumentException">
/// Thrown when the path is null, empty, or whitespace.
/// </exception>
///
/// Examples:
/// document.pdf -> document
/// archive.tar.gz -> archive.tar
/// photo.jpg -> photo
/// README -> README
/// C:\Temp\file.txt -> C:\Temp\file
public static string RemoveFileExtension(string path)
{
if (string.IsNullOrWhiteSpace(path)) {
throw new ArgumentException(
"Path cannot be null or empty.",
nameof(path));
}
// Get the directory portion (if any).
string? directory = Path.GetDirectoryName(path);
// Get the filename without its last extension.
string fileNameWithoutExtension =
Path.GetFileNameWithoutExtension(path);
// If there is no directory, return only the filename.
if (string.IsNullOrEmpty(directory)) {
return fileNameWithoutExtension;
}
// Reconstruct the path without the extension.
return Path.Combine(directory, fileNameWithoutExtension);
}
}
class Program
{
static void Main()
{
Console.WriteLine(
FileHelper.RemoveFileExtension("document.pdf"));
Console.WriteLine(
FileHelper.RemoveFileExtension("archive.tar.gz"));
Console.WriteLine(
FileHelper.RemoveFileExtension(@"C:\Temp\file.txt"));
Console.WriteLine(
FileHelper.RemoveFileExtension("README"));
}
}
/*
run:
document
archive.tar
C:\Temp\file
README
*/