Given a Filesystem Path, Is There a Shorter Way to Extract the Filename Without Its Extension

Given a filesystem path, is there a shorter way to extract the filename without its extension?

Path.GetFileName

Returns the file name and extension of a file path that is represented
by a read-only character span.



Path.GetFileNameWithoutExtension

Returns the file name without the extension of a file path that is
represented by a read-only character span.



The Path class is wonderful.

How to extract the filename from a path


string filename = System.IO.Path.GetFileName("/Images/She.jpg");

c# is there a way to get more than one files name without their path and their extension in an array?

You can use a bit on Linq and Path.GetFileNameWithoutExtension

string[] directory = Directory.GetFiles(@"C:\Program Files (x86)\programloc\shortcuts", "*.lnk")
.Select(System.IO.Path.GetFileNameWithoutExtension)
.ToArray();

Return filename without extension from full path in C#


return Path.GetFileNameWithoutExtension (fullpath);

zsh: Splitting a path that may not have an extension


It seems there should be an easier option than a three-part nested substitution.

Perhaps, but unfortunately, there really isn't. /p>

Here's how I would do it, but again, a nested substitution cannot be avoided:

% split() { 
local split=( "$1:r" "${${1#$1:r}[1]}" "$1:e" )
print "${(q@)split}"
}
% split foo.orig.c
foo.orig . c
% split dir.c/foo
dir.c/foo '' ''

When i try to use Regex.Replace it throws out System.ArgumentException

Like @GSerg pointed out, a typical directory path is unlike to be a valid regex pattern, and even if it is, it is unlikely to do the replace like you would expect.
You should use the plain string.Replace instead.

However, there are better approaches than string replacement. Depending on what you like to do:

  1. to obtain the file name only:

    Path.GetFileName(mod) // BALOO.jar
    Path.GetFileNameWithoutExtension(mod) // BALOO
  2. to obtain the relative path to mod from current directory:

    MakeRelative(mod, Directory.GetCurrentDirectory())
    // ...
    public static string MakeRelative(string path, string relativeTo)
    {
    return new Uri(relativeTo).MakeRelativeUri(new Uri(path)).OriginalString;
    }


Related Topics



Leave a reply



Submit