181

I was wondering about the difference between \ and / in file paths. I have noticed that sometimes a path contains /and sometimes it is with \.

It would be great if anyone can explain when to use \ and /.

PC Luddite
  • 5,883
  • 6
  • 23
  • 39
Spider man
  • 3,224
  • 4
  • 30
  • 42
  • 4
    Difference in what context? A webby context? Escaping in C# strings? It is tagged with ASP.NET. – Peter Mortensen Jul 18 '16 at 17:22
  • Top link googling for "Difference between forward slash and backslash in file path": http://www.howtogeek.com/181774/why-windows-uses-backslashes-and-everything-else-uses-forward-slashes/ explains it pretty well – Jonathan Cast Jul 18 '16 at 19:11
  • 7
    How are [tag:c#] and [tag:asp.net] related to the question? – Oriol Jul 18 '16 at 21:46
  • @Oriol I'm supposing that it's asking when to use each one in this particular language. It's broad enough that it can apply to every language, but I added some C# specific info in my answer. – PC Luddite Jul 18 '16 at 22:07
  • 1
    This question may have the better answers, but there's no answer (mine included) here that's not already mentioned in http://stackoverflow.com/questions/1589930/so-what-is-the-right-direction-of-the-paths-slash-or-under-windows – Ash Jul 19 '16 at 00:19
  • @PeterMortensen When I clicked on the link that you provided, I see that it is closed as a Duplicate of this question? Can a question be a duplicate of itself? If the one you referred to was asked 4 years ago, in what sort of world can it be closed as a duplicate of one that was asked yesterday? I'll have to get that **Tachyon Ansible** patented, post-haste. As soon as my great-great grandchild gets around to being born to create it... –  Jul 19 '16 at 14:32
  • 1
    @nocomprende, Peter recommended closing this as a duplicate of the older one (21h ago). This question attracted better, more comprehensive answers than the older one, so other users decided to close the older question as a duplicate of the newer one (5h ago). It's unusual, but not unheard of. – zzzzBov Jul 19 '16 at 14:40
  • 2
    @zzzzBov why was this one not simply redirected to the older one and the better answers placed there? I don't like a system where a question I ask could be closed in the far future as a "duplicate" of something that happened later on. **At least call it something more descriptive, like "superseded" rather than duplicate.** The original "one" cannot be a duplicate of anything, it is the only one. –  Jul 19 '16 at 15:04
  • 1
    @nocomprende, I was only explaining the order of events. If you have questions on how and why this happens, please ask on [meta]. – zzzzBov Jul 19 '16 at 15:18
  • 1
    OP, can you add some details for what you are asking for? E.g. an example would be useful. And why did you tag it with C# and ASP.NET? If the origin of the question was when working with ASP.NET, can you explain a little bit about it? For example, where do the slashes come into the picture? – Peter Mortensen Sep 11 '16 at 18:49

7 Answers7

280

/ is the path separator on Unix and Unix-like systems. Modern Windows can generally use both \ and / interchangeably for filepaths, but Microsoft has advocated for the use of \ as the path separator for decades.

This is done for historical reasons that date as far back as the 1970s, predating Windows by over a decade. In the beginning, MS-DOS (the foundation to early Windows) didn't support directories. Unix had directory support using the / character since the beginning. However, when directories were added in MS-DOS 2.0, Microsoft and IBM were already using the / character for command switches, and because of DOS's lightweight parser (descended from QDOS, designed to run on lower end hardware), they couldn't find a feasible way to use the / character without breaking compatibility with their existing applications.

So, to avoid errors about "missing a switch" or "invalid switch" when passing filepaths as arguments to commands such as these:

cd/                        <---- no switch specified
dir folder1/folder2        <---- /folder2 is not a switch for dir

it was decided that the \ character would be used instead, so you could write those commands like this

cd\
dir folder1\folder2

without error.

Later, Microsoft and IBM collaborated on an operating system unrelated to DOS called OS/2. OS/2 had the ability to use both separators, probably to attract more Unix developers. When Microsoft and IBM parted ways in 1990, Microsoft took what code they had and created Windows NT, on which all modern versions of Windows are based, carrying this separator agnosticism with it.


As backward compatibility has been the name of the game for Microsoft from all of the major OS transitions that they've undertaken (DOS to Win16/DOS, to Win16/Win32, to Win32/WinNT), this peculiarity stuck, and it will probably exist for a while yet.

It's for this reason that this discrepancy exists. It should really have no effect on what you're doing because, like I said, the WinAPI can generally use them interchangeably. However, 3rd party applications will probably break if you pass a / when they expect a \ between directory names. If you're using Windows, stick with \. If you're using Unix or URIs (which have their foundation in Unix paths, but that's another story entirely), then use /.


In the context of C#: It should be noted, since this is technically a C# question, that if you want to write more "portable" C# code that works on both Unix and Windows (even if C# is predominantly a Windows language), you might want to use the Path.DirectorySeparatorChar field so your code uses the preferred separator on that system, and use Path.Combine() to append paths properly.

PC Luddite
  • 5,883
  • 6
  • 23
  • 39
  • 63
    And always combine paths using [`Path.Combine`](https://msdn.microsoft.com/en-us/library/system.io.path.combine(v=vs.110).aspx). – Cheng Chen Jul 18 '16 at 05:54
  • 1
    Interesting. So under DOS or Windows, `foo.exe /bar` might be interpreted as a command-line switch, while `foo.exe \bar` might be interpreted as referring to a file/folder called `bar` which is located in the root directory ``\`` of the current "drive", like ``C:\`` for example. – Jeppe Stig Nielsen Jul 18 '16 at 09:05
  • 6
    It should be noted that this normalisation from `/` to `\ ` is done in the Win32 compat layer, meaning that if you circumvent it, there will be a difference. The best known example of this are extended length paths: `\\?\C:\ ` will work as expected on NTFS but `\\?\C:/` won't. – Voo Jul 18 '16 at 10:13
  • 4
    @PC Luddite: That WinAPI can handle both `/` and `\` is not entirely true. For network path you have to use `\` (eg. \\ bot not //) – raznagul Jul 18 '16 at 10:13
  • 2
    @raznagul True. I didn't really mention network paths in my answer. I stuck mainly with the common filepath type. I'll add that. – PC Luddite Jul 18 '16 at 18:16
  • @JeppeStigNielsen - yes, but it's important to remember that *this is only a user interface convention*. The actual filesystem handling code in the operating system itself is happy to use either, only the user interfaces/command line interpreters care which one you actually use. For filenames embedded in programs you write yourself, it really doesn't matter which you use. – Jules Jul 18 '16 at 23:44
  • @Jules No, the UI and CLI can use both interchangeably, like I said. They don't care either. It's just always displayed on windows with `\ `. The Command Prompt (if you use quotes), Windows Explorer, and the Run dialog will all happily accept both. It just might break if you pass a path with `/` to a 3rd party program. The "filesystem handling code" is the WinAPI I was talking about. – PC Luddite Jul 19 '16 at 03:48
  • @PCLuddite To add to the historic anecdotes: Ironically, the Backslash that was used by Microsoft as a sidestep is of course not unused in Unix & Co. either… And since the MS world has become more and more unix-y, backslashes are used there as an escape character also. This results in syntactic workaround constructions like `@"...."` strings in C#, for example. – Stefan Jul 19 '16 at 19:19
  • 1
    @Stefan `\ ` is not really used by Windows as an escape character the same way unix uses it like that. Sure, there are many programming languages that use this syntax (inherited from C which came from Unix), but that's not how you escape things in the Windows NT Command Prompt, you use the `^` character, and in PowerShell, you use the `\`` (backtick). – PC Luddite Jul 20 '16 at 01:26
  • @Stefan I would also counter that "the MS world has become more and more unix-y". Sure, there are instances where that's true, but you could also point out where unix has become more "windows-y". Operating systems take ideas from each other over time. It's a natural process. – PC Luddite Jul 20 '16 at 01:28
  • @PCLuddite No objection. I was indeed referring to the usage of the backslash in programming languages rather than in shell scripts / command prompts. However, when using strings to represent file system paths, this collides in Windows. – Stefan Jul 20 '16 at 10:11
  • Then what do you do if you're developing a program to be cross-compatible with Windows and Unix-likes? I assume forward slash? Will there be any problems with using it on Windows? – Aaron Franke Dec 03 '17 at 00:13
  • @AaronFranke use `Path.DirectorySeparatorChar` for cross platform in c# – PC Luddite Dec 03 '17 at 00:14
  • @AaronFranke but it really depends on the language. In C you can use preprocessor directives. – PC Luddite Dec 03 '17 at 00:25
  • For real though, I wonder if there's a single developer in existence who writes paths like `$@"~{Path.DirectorySeparatorChar}Images{Path.DirectorySeparatorChar}Icons{Path.DirectorySeparatorChar}Themes{Path.DirectorySeparatorChar}Dark{Path.DirectorySeparatorChar}foobar.png"` – Extragorey Apr 16 '19 at 01:12
  • @Extragorey It would neither be reasonable nor necessary in any well formed code to write that – PC Luddite Apr 16 '19 at 20:44
21

MS-DOS 1.0 retained the command line option (or switch) character convention of '/' from CP/M. At that time there was no directory structure in the file system and no conflict.

When Microsoft developed the more Unix like environment with MS-DOS (and PC-DOS) 2.0, they needed to represent the path separator using something that did not conflict with existing command line options. Internally, the system works equally well with either '/' or '\'. The command processor (and many applications) continued to use the '/' as a switch character.

A CONFIG.SYS entry SWITCHAR=- could be used to override the / default to improve Unix compatibility. This makes built in commands and standard utilities use the alternate character. The Unix path separator could then be unambiguously used for file and directory names. This entry was removed in later versions, but a DOS call was documented to set the value after booting.

This was little used and most third-party tools remained unchanged. The confusion persists. Many ports of Unix tools retain the '-' switch character while some support both conventions.

The follow-on PowerShell command processor implements rigorous escaping and switch parameters and largely avoids the confusion except where legacy tools are used.

Neither the question nor the answer relate to C#.

Pekka
  • 3,529
  • 27
  • 45
  • 4
    As a historical note, the use of `/` as an option introducer in various PDP-11 operating system such as RSTS (1970) and RSX (1972) precedes that in CP/M (1973). – PJTraill Jul 19 '16 at 20:09
9

On Unix-based systems \ is an escape character, that is, \ tells the parser that this is a space and not the end of the statement. On Unix systems / is the directory separator.

On Windows \ is the directory separator, but the / cannot be used in file or directory names.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 1
    `\ ` and `/` (as well several other symbols) can't be used in filenames because DOS didn't have the same complex parser that Unix users are so used to. The lack of a good parser was the result of MS-DOS being descended from QDOS ("Quick and Dirty Operating System"). It was meant to get things running quickly and on limited hardware. All this of course still exists in the present day for backward compatibility. – PC Luddite Jul 18 '16 at 06:10
  • 3
    well, worth mentioning that in later Windows versions the `/` was added as an "Alternate_Directory_Separator" – Tomer W Jul 18 '16 at 18:23
  • @PCLuddite maybe we should be thinking of forward compatibility instead? –  Jul 18 '16 at 20:35
  • @nocomprende Not when a large part of your customer base is businesses. It's not important to most of them how "modern" things are, just that they function with their current software. Break that compatibility and those businesses just won't upgrade. You lose your customer base. Home users who expect this compatibility as well won't upgrade either. That's one of the big reasons Vista failed so badly. It broke compatibility with a lot of perfectly good software, and no one bought it. – PC Luddite Jul 18 '16 at 22:02
  • @Luaan I am thinking of standards so well-designed that they stood for a very long time. Unix has been around a while, and C. Improved, but basically the same. The Analog Television standard stood for almost 70 years, and had color compatibly added. FM broadcast is even older, and had stereo compatibly added. Analog telephone is about 150 years old. Businesses have saved a lot on not having to change their telephone equipment every few years. I am not aware of any similar irritations to \ / in those standards. Big-endian vs Little-endian should have been decided by fiat, and never revisited. –  Jul 19 '16 at 14:23
  • @Luaan then let's stick with ignorance and choose things that are simple and last for a long time? If a standard is "good enough" why not just stick with it instead of creating new kinds and colors of wheels? The wheel works, just use it. –  Jul 19 '16 at 14:36
  • @Luaan I said color was able to be added in a compatible way, unlike the directory structure in DOS. Adding color did not affect monochrome TVs = "compatible". Adding stereo did not affect mono radios. That is a sign of a well-designed standard: it allows for improvements that do not affect existing users, over a very long period of time (a lifetime). We need more standards like that, and less frill. –  Jul 19 '16 at 14:41
  • @Luaan saving a few DOS apps from breaking due to the command line arg character turned out to be a much smaller consideration than file path name compatibility. Someone who was thinking far enough ahead could have foreseen that. File paths show up all over the place, but it is hard to even get to the command line nowadays. On the face of it, if you have been looking at the problem 40 years ago, which would you have said was more important in the long run: command line switches, or handling file paths? Common sense would pick the right winner. –  Jul 19 '16 at 15:11
  • 1
    @nocomprende What about filepaths are incompatable? Incompatable with what? And like I said before, saving "a few DOS apps" (which was really more like thousands) from breaking was really important to consumers at the time. It's what made Microsoft successful today and Unix (and all others really) start on the decline (even if there's been a resurgence in the last decade). I fail to see how that's not looking at it with common sense. – PC Luddite Jul 19 '16 at 15:15
  • @PCLuddite The nice thing about standards is there are so many to choose from. But I am really glad that the street signs and stop lights are standardized, and that my 20 year old car can do everything that a new car can. Someone was thinking ahead. –  Jul 19 '16 at 15:30
  • @nocomprende Streets, street signs and stop lights are actually not very well standardized if you live in the US. Their maintenance can fall under either federal, state, or even local government (ever been driving on a street that's all nice and paved then turns crappy when you cross city lines?). And the car market is not as fickle as the technology market. Consumers want a new thing every day when it comes to computers, and that's way more difficult to predict than what people want in a car, which ultimately boils down to only how well it drives. – PC Luddite Jul 19 '16 at 15:37
  • 1
    @nocomprende And your argument about filepaths not being standardized is completely void. They're standardized on Windows, and they're standardized on Unix. If you're talking about a cross-platform standard, that's not really that useful or easy to implement. Who's to say that one standard is really "better" than another? – PC Luddite Jul 19 '16 at 15:40
  • @PCLuddite if niether one is really better, then just pick one and move on. I refer again to big-endian / little-endian. It should never have happened. Pick one and move on. Red means Stop? Green Go? Whatever, as long as it is consistent, world without end, amen, amen. If you are creating infrastructure or industry standards, it matters. So, assume that you are always doing that, and think carefully and far ahead. People used to do that. –  Jul 19 '16 at 15:49
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/117731/discussion-between-pc-luddite-and-no-comprende). – PC Luddite Jul 19 '16 at 15:50
9
  • A URL, standardized in RFC 1738, always uses forward slashes, regardless of platform.
  • A file path and a URI are different. \ is correct in a Windows file path and / is correct in a URI.
  • Several browsers (namely, Firefox & Opera) fail catastrophically when encountering URIs with backslashes.
  • System.IO.Path.DirectorySeparatorChar to get current path separator

This can be relevant resource.

Community
  • 1
  • 1
Sami
  • 3,686
  • 4
  • 17
  • 28
  • 13
    Fail catastrophically? Firefox translates `\​​` to `/` automatically. In my book this is called "works seamlessly". – This company is turning evil. Jul 18 '16 at 11:31
  • 25
    my house caught on fire the last time I used \ in Firefox – user3163495 Jul 18 '16 at 13:27
  • 1
    @CarstenS, Firefox does not convert backslash to forward slash in URL automaticaly and does not open the link. This add-on corrects the URL with backslash and open page. https://addons.mozilla.org/en-US/seamonkey/addon/backslash-to-forward-slash/?src=cb-dl-name – Sami Jul 20 '16 at 06:58
  • What exactly do you mean by "fail catastrophically"? What happens? Does the browser crash and exit? – Peter Mortensen Sep 11 '16 at 18:36
8

You shouldn't be using either in C#. You should always use the Path class. This contains a method called Path.Combine that can be used to create paths without specifying the separator yourself.

Example usage:

string fullPath = System.IO.Path.Combine("C:", "Folder1", "Folder2", "file.txt");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
TheLethalCoder
  • 6,668
  • 6
  • 34
  • 69
7

Apart from the answers given, it is worth mentioning that \ is widely used for special characters (such as \n \t) in programming languages, text editors and general systems that apply lexical analysis.

If you are programming for instance, it is inconvenient at times to need to even need to escape backslash with another one (\\) in order to use it properly - or need to use escaping strings, such as C# @"\test".

Of course, as mentioned before, web URIs use forward slash by standard but both slashes work in the latest and most common command line tools.

UPDATE: After searching a little bit, it seems out the whole story between / and \ goes back in "computer history", in the ages of DOS and the Unix-based systems at that time. HowToGeek has an interesting article about this story.

In short terms, DOS 1.0 was initially released by IBM with no directory support, and / was used for another ("switching") command functionality. When directories were introduced in 2.0 version, / was already in use, so IBM chose the visually closest symbol, which was \. On the other hand, Unix standardly used / for directories.

When users started to use many different systems, they started becoming confused, making the OS developers to attempt making the systems work in both cases - this even applies in the part of URLs, as some browsers support the http:\\www.test.com\go format. This had drawbacks though in general, but the whole thing stands today still for backward compartibility causes, with an attempt for support of both slashes on Windows, even though they are not based on DOS anymore.

Nick Louloudakis
  • 5,856
  • 4
  • 41
  • 54
  • "both slashes work in file system paths." is incorrect, because Unix is pretty angry when you use `\` as well as many `make` shells... you are right that recent Windows have defined the ALTERNATE_PATH_SEPARATOR environment variable which defaults to `/` hence Windows can probably accept both. – Tomer W Jul 18 '16 at 18:27
  • 1
    @TomerW Windows NT has always been POSIX-compatible (though early POSIX was a mess anyway, and some of it stuck in Windows for backwards compatibility). That included supporting `/` paths everywhere in the system - of course, applications could misunderstand those paths at their leisure, so it wasn't used too much. Non-CLI applications that didn't try to do their own (broken) validation of paths worked fine from the get go. – Luaan Jul 19 '16 at 11:55
  • @Luaan Windows had the ability to support many POSIX features, but I would hardly say it was "POSIX-compatible". Sure, there were a few POSIX subsystems one could use over the years, but those were far from ideal. Windows 10 will be supporting Ubuntu bash though later this summer along with native support for the Linux tools that come with Ubuntu, so you may be able to argue that in the future, but you certainly can't say "always". – PC Luddite Jul 19 '16 at 15:25
  • @Luaan Unless by "compatible" you mean "cygwin works". – PC Luddite Jul 19 '16 at 15:27
  • @PCLuddite No, it was 100% POSIX.1c compatible. That doesn't mean that all unix applications work on it - most unix applications are *not* POSIX compliant :) – Luaan Jul 19 '16 at 17:42
  • @Luaan Hey, do you have the ability to remove comments? If so, I'd recommend removing the argument in that other answer with nocomprende. I think that's better left to chat. – PC Luddite Jul 19 '16 at 17:50
  • @Luaan You're technically right, [this](https://en.wikipedia.org/wiki/Microsoft_POSIX_subsystem) did offer bare-bones POSIX compliance from NT 3.5 up until 2000, but it was hardly used. I'm thinking that this new Linux subsystem gains more traction though. – PC Luddite Jul 19 '16 at 17:57
  • @PCLuddite Yeah, in part exactly because nobody cared about POSIX (even though many claimed to) - most applications were never POSIX compliant, neither on Unix nor Windows. That's also what led to the very limited attention the subsystem got from MS later on - customers didn't care, and MS cared about what the customers care about. The new Linux subsystem is interesting, but I expect that it will only really be used by developers, and maybe some specialists like, say, physicists. The truth is, the *nix world doesn't exactly have a track record of good UX :) – Luaan Jul 19 '16 at 19:38
  • The whole converstation inspired me to search it a little bit and update the answer more. :) – Nick Louloudakis Jul 19 '16 at 21:32
6

\ is used for Windows local file paths and network paths as in:

C:\Windows\Temp\ or \\NetworkSharedDisk\Documents\Archive\

/ is what is required by standard URIs as in:

http://www.stackoverflow.com/

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ash
  • 5,786
  • 5
  • 22
  • 42
  • 2
    @NikhilVartak, I've added examples although I thought my initial answer addressed all of the OP's questions. – Ash Jul 18 '16 at 04:40
  • 3
    Windows also recognizes `/` in paths (at least 7 does). – Kenneth K. Jul 18 '16 at 11:58
  • This answer is far from complete. – reinierpost Jul 18 '16 at 14:11
  • Were you meant to link to some resources, besides just the Stack Overflow main page? – Tas Jul 18 '16 at 21:51
  • @reinierpost, my answer is based on the OP's question and the associated tags. Like few of the other answers here, I could copy something from http://stackoverflow.com/questions/1589930/so-what-is-the-right-direction-of-the-paths-slash-or-under-windows and paste it here but it seemed excessive. @tas, I intended to link to stackoverflow page or any website hyperlink to illustrate use of `/` in standarad URIs as I've stated in the answer. – Ash Jul 19 '16 at 00:14