Search code examples
c#file-manipulation

Use Path.GetFileNameWithoutExtension method in C# to get the file name but the display is not complete


This is the simple C# code I wrote :

string file = @"D:\test(2021/02/10).docx";
            var fileName = Path.GetFileNameWithoutExtension(file);
            Console.WriteLine(fileName);

I thought I would get the string "test(2021/02/10)" , but I got this result "10)". How can I solve such a problem?


Solution

  • I just wonder why would you want such behavior. On windows slashes are treated as separator between directory and subdirectory (or file).

    So, basically you are not able to create such file name.

    And since slashes are treated as described, it is very natural that method implementation just checks what's after last slash and extracts just filename.

    If you are interested on how the method is implemented take a look at source code