JKennedy
JKennedy

Reputation: 18799

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

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

Upvotes: 4

Views: 2628

Answers (2)

JKennedy
JKennedy

Reputation: 18799

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 = System.IO.Path.DirectorySeparatorChar;
    var file = System.IO.Path.GetFileNameWithoutExtension(memberName.Replace('\\', seperatorChar));
    Track(file);
}

Upvotes: 6

Daniel A. White
Daniel A. White

Reputation: 190943

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.

Upvotes: 1

Related Questions