Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Path.GetFileName(string) returning the full path?

Tags:

c#

I have created a PCL (Portable Class Library) to do some logging for my application and have the method:

public static void EnterPage([CallerFilePath]string memberName = "")
{
   var file = System.IO.Path.GetFileName(memberName);
   Track(file);
}

Where memberName = "d:\\teamFoundation\\MyApp\\MyApp-Reporting\\MyApp.Core\\App.cs"

and GetFileName returns the full path - d:\\teamFoundation\\MyApp\\MyApp-Reporting\\MyApp.Core\\App.cs instead of App.cs

Is there any reason why this wouldnt be working for a PCL? I am currently running on my Android device

like image 588
User1 Avatar asked Mar 15 '23 08:03

User1


2 Answers

On Windows the Path separator is \ but this is not the same for Android

From the android documentation you can see that the separator is actually / and this is the same for iOS

The value for memberName is passed at compile time and therefore depends on the type of machine you build your solution on. where as the call to System.IO.Path.GetFileName is done at runtime.

Therefore to resolve this issue you must replace the separator char in your File Paths:

public static void EnterPage([CallerFilePath]string memberName = "")
{
    char seperatorChar = (char)typeof(System.IO.Path).GetTypeInfo().GetDeclaredField("DirectorySeparatorChar").GetValue(null);
    var file = System.IO.Path.GetFileNameWithoutExtension(memberName.Replace('\\', seperatorChar));
    Track(file);
}
like image 99
User1 Avatar answered Mar 21 '23 00:03

User1


You will need to do this manually if working cross platform. The value for memberName is passed at compile time where the call to System.IO.Path.GetFileName is done at runtime. The path separators between Windows and Android are different.

like image 43
Daniel A. White Avatar answered Mar 21 '23 01:03

Daniel A. White