Cross-platform file name handling in .NET Core

2019-02-21 12:39发布

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 perfectly on Windows, however it doesn't create a file on Ubuntu Linux:

var tempFilename = $@"..\Data\uploads\{filename}";
using (FileStream fs = System.IO.File.Create(tempFilename))
{
    file.CopyTo(fs);
    fs.Flush();                    
}

4条回答
We Are One
2楼-- · 2019-02-21 12:55

You can also use Path.DirectorySeparatorChar as below:

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

Reference: MSDN

查看更多
劫难
3楼-- · 2019-02-21 12:59

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.

查看更多
成全新的幸福
4楼-- · 2019-02-21 13:01

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

查看更多
趁早两清
5楼-- · 2019-02-21 13:07

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)

查看更多
登录 后发表回答