Cross-platform file name handling in .NET Core

前端 未结 6 1410
我在风中等你
我在风中等你 2020-12-15 03:02

How to handle file name in System.IO classes in a cross-platform manner to make it work on Windows and Linux?

For example, I write this code that works

相关标签:
6条回答
  • 2020-12-15 03:23

    Windows using Backslash. Linux using Slash. Path.Combine set the right symbol :
    Path.Combine Method - MSDN

    0 讨论(0)
  • 2020-12-15 03:25

    You can also use Path.DirectorySeparatorChar as below:

     Console.WriteLine("..{0}Data{0}uploads{0}{{filename}}", Path.DirectorySeparatorChar);
    

    Reference: MSDN

    0 讨论(0)
  • 2020-12-15 03:27

    Of course forward slashes work fine - except when they don't. It is an older problem, but certainly LoadLibrary actually bit me in this regard. Please see https://stackoverflow.com/a/34708551/1318024 which discusses this. Even though we do expect Windows to handle path separators gracefully (which we do not expect for *nix!) it is best to use the path separator appropriate for the platform.

    0 讨论(0)
  • 2020-12-15 03:32

    The original post is over a year old but I still ran into this issue. It seems to me like the use of dots in relative paths is also an issue.

    A path like

    ".\\input\\mydata.csv" 
    

    worked well on windows but not on unix. When changing the dot-notation for current directory to:

    Path.GetFullPath(Directory.GetCurrentDirectory())
    

    I had more success.

    0 讨论(0)
  • 2020-12-15 03:33

    Lots of good answers. I would just like to add that one can avoid having to specify the directory separator character by using Path.Combine

    Example with the file relatively located at ".\..\toto\app.config":

    Path.Combine("..", "toto", "app.config");
    

    Unfortunately, Path.Combine does not resolve a relative path to an absolute Path in .Net Core. Path.GetFullPath is here for that:

    Path.GetFullPath(Path.Combine("..", "toto", "app.config"))
    
    0 讨论(0)
  • 2020-12-15 03:44

    You can simply use slashes. Relative paths will work identically, and absolute paths can only be relative to the root of the main drive (as absolute paths starting with "c:" are not portable)

    0 讨论(0)
提交回复
热议问题