Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileInfo.BaseName exists in PowerShell but not in straight .NET

Why is it that in .NET the System.IO.FileInfo object does not have a BaseName property, but I can use the property through PowerShell, e.g.:

$FolderItems = Get-ChildItem -Path "C:\" | Where-Object {$_ -isnot [IO.DirectoryInfo]}

foreach ($FolderItem in $FolderItems)
{
    write-host $FolderItem.BaseName 
}
like image 663
rory.ap Avatar asked Feb 12 '14 21:02

rory.ap


2 Answers

Powershell adds that property for you. If you run get-member on a fileinfo object, you can see that it's a script property, and even the script itself:

get-item testfile1.txt | Get-Member BaseName | format-list

TypeName   : System.IO.FileInfo
Name       : BaseName
MemberType : ScriptProperty
Definition : System.Object BaseName {get=if ($this.Extension.Length -gt 0){$this.Name.Remove($this.Name.Length - 
         $this.Extension.Length)}else{$this.Name};}
like image 199
mjolinor Avatar answered Nov 15 '22 07:11

mjolinor


Because BaseName isn't a Property, it's a ScriptProperty.

Name                      MemberType     Definition                                                                     
----                      ----------     ---------- 
BaseName                  ScriptProperty System.Object BaseName {get=if ($this.Extension.Length -gt 0){$this.Name.Remove($this.Name.Length - $this.Extension.Length)}else{$this.Name};}

To clarify, it is a calculated response that PowerShell gives you derived from other properties of the object. It is not itself a direct property of a System.IO.FileInfo object. When you ask PowerShell for the BaseName value it looks at the Name value, checks if there is an Extension value, and then truncates the Extension value from the Name value and returns the result.

Edit: Amazing how somebody else answers the question 2 minutes after me with a virtually identical answer and they get twice as many up votes and are marked as the answer. </nerdrage>

like image 32
TheMadTechnician Avatar answered Nov 15 '22 07:11

TheMadTechnician