Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross-platform file name handling in .NET Core

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();                     } 
like image 295
Roman Kolesnikov Avatar asked Jul 03 '16 09:07

Roman Kolesnikov


People also ask

How does NET Core work on cross-platform?

NET Core is cross-platform. It runs on Windows, OS X and multiple distributions of Linux. It also supports different CPU architectures. We're adding more Linux distribution and CPU architecture support with the eventual goal of .

What is System IO path?

A path is a string that provides the location of a file or directory. A path does not necessarily point to a location on disk; for example, a path might map to a location in memory or on a device. The exact format of a path is determined by the current platform.

What is path C#?

C# path class comes under System.IO namespace and System. Runtime. dll assembly. This class is used to perform operations on string instances that have file path or directory path information. A path is a string that holds the location of the file or directory and it can be an absolute or relative location.


1 Answers

You can also use Path.DirectorySeparatorChar as below:

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

Reference: MSDN

like image 199
onemorecupofcoffee Avatar answered Oct 10 '22 18:10

onemorecupofcoffee