String Escape · Tutorial
How to put a Windows file path into a Java or C# string
4 min readbeginnerUpdated
You paste a Windows path like C:\Users\Amara\Documents into your code and get a compile error, or worse, a path where \U or \t has silently turned into something else. This tutorial shows how to escape the path correctly for your language, and when a raw string is the better choice.
What you need
- The String Escape tool
- The path or text you want to use (the Try it button loads a path containing quotes)
Steps
Paste the path
Paste the path into the left box, exactly as it appears in File Explorer. The sample path also contains a file name in double quotes, which makes things worse.
Choose your language and Escape
Choose Java (or C#) and keep the direction on Escape. Every backslash is doubled and the double quotes are escaped with a backslash.
C:\\Users\\Amara\\Documents\\Reports\\Q3 \"final\".xlsxPaste it into your code
Put the result between double quotes in your source code. The compiler turns each
\\back into a single backslash, so at runtime the string is exactly the original path.String path = "C:\\Users\\Amara\\Documents\\Reports\\Q3 \"final\".xlsx";Consider a raw or verbatim string
Many languages have a string form where backslashes aren't special. In C#, use a verbatim string, where only quotes need doubling:
@"C:\Users\Amara\...". In Python, use a raw string:r"C:\Users\Amara". Java 15+ text blocks still process escapes, so escaping is the safest option there.Or use forward slashes
Java, Python, Node.js and .NET all accept forward slashes in Windows paths, as in
C:/Users/Amara/Documents. Better still, build paths with your language's path functions, such asPath.of(...)oros.path.join(...).
Try it yourself
Opens the String Escape with this tutorial's sample loaded.
Common mistakes
- Escaping twice
- If you see
\\\\in your code, the text was escaped twice. Escape the original path once. - Choosing the wrong language
- JavaScript and Python also escape single quotes, while SQL doubles them instead of using backslashes. Pick the language you're actually writing.
- Hard-coding user folders
- Paths like
C:\Users\Amaraonly work on one machine. Read user folders from environment variables or configuration instead.
Next steps
Go back to the String Escape, or keep going with one of these:
FAQ
Why did "\t" in my path turn into a gap?
In most languages, \t inside a normal string is a tab character. A path like C:\temp contains \t by accident. Escaping it as \\t fixes this.