Over the years, and again recently, I have heard discussion that everyone should use Path.Combine instead of joining strings together with "\\", for example:
string myFilePath = Path.Combine("c:", "myDoc.txt");
// vs.
string myFilePath = "C:" + "\\myDoc.txt";
I'm failing to see the benefit that the former version provides over the latter and I was hoping someone could explain.
Building a path with Path.Combine is more readable and less error-prone. You don't need to think about directory separator chars(\\ or \ or / on unix, ...) or if the first part of the path does or does not end in \ and whether the second part of the path does or does not start with \.
You can concentrate on the important part, the directories and filenames. It's the same advantage that String.Format has over string concatenation.
When you don't know the first directory (e.g. it comes from user input), you may have C:\Directory or C:\Directory\ and Path.Combine will solve the trailing slash problem for you. It does have quirks with leading slashes for the next arguments though.
Second, while usually not a problem for most applications, with Path.Combine you aren't hard-coding the platform directory separator. For an application that can be deployed to other operating systems than windows this is convenient.
Other platforms can use a different Separator, for example / instead of \ so the reason for not using \\ is to be S.O. independent
In this case, it does not really matter, but why don't you just write:
string myFilePath = "C:\\myDoc.txt";
The Path.Combine() method is useful if you are working with path variables and you don't want to check for backslashes (or whatever slashing required, depending on the platform):
string myFilePath = Path.Combine(path, filename);
Related
Using System.IO, I tried the following code:
string[] files = Directory.GetFiles("\\folder\\folder_2\\folder_3");
And got the following exception:
"System.IO.DirectoryNotFoundException - It was not possible to locate part of the path 'C:\folder\folder_2\folder_3)' "
I don't know why "c:\" was added to the original string, and I can't seem to keep the method from doing so. What am I doing wrong?
Any help is much appreciated.
A backslash (\) at the start of a path makes it an absolute path. Remove the first \ if you want a relative path:
string[] files = Directory.GetFiles("folder\\folder_2\\folder_3");
You need to escape each of the beginning backslashes in your path, you only escaped a single slash. Use either correct escaping:
string[] files = Directory.GetFiles("\\\\folder\\folder_2\\folder_3");
Or you can use a verbatim string literal:
string[] files = Directory.GetFiles(#"\\folder\folder_2\folder_3");
Full explanation found in MSDN Documentation
In addition to the answers provided, you could use verbatim string literals, which will pass the string exactly without the need for escaping with all the messy backslashes.
In your case this would be
string[] files = Directory.GetFiles(#"folder\folder_2\folder_3");
Notice that the # is outside of quotes, but stuck to the opening quotes, this tells C# to use it, (pardon the pun) literally. The syntax highlighting for this kind of string will also change in Visual Studio, just FYI.
edit: saw a comment by another user advising you to use the #, it's the same thing. Sorry did not see this earlier.
Read about them here at MSDN
I have a question about using Sox. I need to mix many audio files and every file has it's own specific time when it should be added. I'm using piping and everything goes fine until I need to grab files with absolute paths with spaces in folder names. In this case I need to use double quotes twice (in path and to allocate piping). Here's example:
-m "initial.wav" "|sox "path with spaces\file1.mp3" -p pad 8.52 0" "|sox "another path with spaces\file2.mp3" -p pad 19.07 0" "|sox "file3.mp3" -p pad 36.52 0" "output.mp3"
And of course these quotes around file paths ruin command.
How can I fix this? Maybe it's possible to use single quotes somehow or maybe I'm missing something obvious...
Will may be useful to add that I'm runing sox from C# app, thus everything happens in Windows.
Usually, it is possible to escape the inner double quotes somehow. (Most?) *nix shells use the backslash for that purpose, i.e. you would write ... "|sox \"path with spaces/file1.mp3\" ...". Of course, Windows uses the backslash for different purposes (delimiting path components), so there may be a slightly different way to escape quotes.
I have a path and I want to add to it some new sub folder named test.
Please help me find out how to do that.
My code is :
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
Console.WriteLine(path+"\test");
The result I'm getting is : "c:\Users\My Name\Pictures est"
Please help me find out the right way.
Do not try to build pathnames concatenating strings. Use the Path.Combine method
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
Console.WriteLine(Path.Combine(path, "test"));
The Path class contains many useful static methods to handle strings that contains paths, filenames and extensions. This class is very useful to avoid many common errors and also allows to code for a better portability between operating systems ("\" on win, "/" on Linux)
The Path class is defined in the namespace System.IO.
You need to add using System.IO; to your code
You need escape it. \t is an escape-sequence for Tabs 0x09.
path + "\\test"
or use:
path + #"\test"
Better yet, let Path.Combine do the dirty work for you:
Path.Combine(path, "test");
Path resides in the System.IO namespace.
There are two options:
Use the # symbol e.g.: path + #"\test"
use a double backslash e.g.: path + "\\test"
string add;
add += "\\"; //or :"\\" means backslash
Backslash '\' is an escape character for strings in C#.
You can:
use Path.Combine
Path.Combine(path, "test");
escape the escape character.
Console.WriteLine(path+"\\test");
use the verbatim string literal.
Console.WriteLine(path + #"\test");
the backslash is an escape character, so use
Console.WriteLine(path+"\\test");
or
Console.WriteLine(path+#"\test");
How can I split a path by "\\"? It gives me a syntax error if I use
path.split("\\");
You should be using
path.Split(Path.DirectorySeparatorChar);
if you're trying to split a file path based on the native path separator.
Try path.Split('\\') --- so single quote (for character)
To use a string this works:
path.Split(new[] {"\\"}, StringSplitOptions.None)
To use a string you have to specify an array of strings. I never did get why :)
There's no string.Split overload which takes a string. (Also, C# is case-sensitive, so you need Split rather than split). However, you can use:
string bits = path.Split('\\');
which will use the overload taking a params char[] parameter. It's equivalent to:
string bits = path.Split(new char[] { '\\' });
That's assuming you definitely want to split by backslashes. You may want to split by the directory separator for the operating system you're running on, in which case Path.DirectorySeparatorChar would probably be the right approach... it will be / on Unix and \ on Windows. On the other hand, that wouldn't help you if you were trying to parse a Windows file system path in an ASP.NET page running on Unix. In other words, it depends on your context :)
Another alternative is to use the methods on Path and DirectoryInfo to get information about paths in more file-system-sensitive ways.
To be on the safe side, you could use:
path.Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar });
On windows, using forward slashes is also accepted, in C# Path functions and on the command line, in Windows 7/XP at least.
e.g.:
Both of these produce the same results for me:
dir "C:/Python33/Lib/xml"
dir "C:\Python33\Lib\xml"
(In C:)
dir "Python33/Lib/xml"
dir "Python33\Lib\xml"
On windows, neither '/' or '\' are valid chars for filename. On Linux, '\' is ok in filenames, so you should be aware of this if parsing for both.
So if you wanted to support paths in both forms (like I do) you could do:
path.Split(new char[] {'/', '\\'});
On Linux it would probably be safer to use Path.DirectorySeparatorChar.
Path.Split(new char[] { '\\\' });
Better just use the existing class System.IO.Path, so you don't need to care for any system specifications.
It provides methods to access any part of a file path like GetFileName(string path) etc.
A complete solution could look like this:
//
private static readonly char[] pathSeps = new char[] {
Path.DirectorySeparatorChar,
Path.AltDirectorySeparatorChar,
Path.VolumeSeparatorChar,
};
//
///<summary>Split a path according to the file system rules.</summary>
public static string[] SplitPath( string path ) {
if ( null == path ) return null;
return path.Split( pathSeps, StringSplitOptions.RemoveEmptyEntries );
}
Some of the other proposed solutions in this article use the syntax:
path.Split(new char[] {'/', '\'});
Although this will work, it has various disadvantages:
It does not allow your application to adapt to various target platforms. Currently, our applications are basically running on UNIX and Windows OSs (Win, macOS, iOS, linux variations). So there is a fixed set of path characters. But this might change when dotNET were ported to other operating systems. So it is best to use the predefined constants.
Performance of the inline syntax is worse. This might not be of interest for a handful of files, but when working with millions of files there are noticeable differences. The managed memory will go up until next GC. When looking at the generated assembly code you will find "call CORINFO_HELP_NEWARR_1_VC" for each of the 'new' statements, even in Release mode. This happens whenever you new-up any array, because arrays are not immutable. My proposed solution prevents this by declaring the array as readonly and static.
Reusability of the inline syntax also is worse, because you might want to use the path separators array in other contexts.
StringSplitOptions.RemoveEmptyEntries should be used to account for UNC paths and possible typos within the incoming path. The operating systems do not allow duplicate path separators, but there might be a typo from the user or a duplicate concatenation of path separator characters, for example when concatenating the path and filename.
I am currently looking for a regex that can help validate a file path e.g.:
C:\test\test2\test.exe
I decided to post this answer which does use a regular expression.
^(?:[a-zA-Z]\:|\\\\[\w\.]+\\[\w.$]+)\\(?:[\w]+\\)*\w([\w.])+$
Works for these:
\\test\test$\TEST.xls
\\server\share\folder\myfile.txt
\\server\share\myfile.txt
\\123.123.123.123\share\folder\myfile.txt
c:\folder\myfile.txt
c:\folder\myfileWithoutExtension
Edit: Added example usage:
if (Regex.IsMatch (text, #"^(?:[a-zA-Z]\:|\\\\[\w\.]+\\[\w.$]+)\\(?:[\w]+\\)*\w([\w.])+$"))
{
// Valid
}
*Edit: * This is an approximation of the paths you could see. If possible, it is probably better to use the Path class or FileInfo class to see if a file or folder exists.
I would recommend using the Path class instead of a Regex if your goal is to work with filenames.
For example, you can call Path.GetFullPath to "verify" a path, as it will raise an ArgumentException if the path contains invalid characters, as well as other exceptiosn if the path is too long, etc. This will handle all of the rules, which will be difficult to get correct with a Regex.
This is regular expression for Windows paths:
(^([a-z]|[A-Z]):(?=\\(?![\0-\37<>:"/\\|?*])|\/(?![\0-\37<>:"/\\|?*])|$)|^\\(?=[\\\/][^\0-\37<>:"/\\|?*]+)|^(?=(\\|\/)$)|^\.(?=(\\|\/)$)|^\.\.(?=(\\|\/)$)|^(?=(\\|\/)[^\0-\37<>:"/\\|?*]+)|^\.(?=(\\|\/)[^\0-\37<>:"/\\|?*]+)|^\.\.(?=(\\|\/)[^\0-\37<>:"/\\|?*]+))((\\|\/)[^\0-\37<>:"/\\|?*]+|(\\|\/)$)*()$
And this is for UNIX/Linux paths
^\/$|(^(?=\/)|^\.|^\.\.)(\/(?=[^/\0])[^/\0]+)*\/?$
Here are my tests:
Win Regex
Unix Regex
These works with Javascript
EDIT
I've added relative paths, (../, ./, ../something)
EDIT 2
I've added paths starting with tilde for unix, (~/, ~, ~/something)
The proposed one is not really good, this one I build for XSD, it's Windows specific:
^(?:[a-zA-Z]\:(\\|\/)|file\:\/\/|\\\\|\.(\/|\\))([^\\\/\:\*\?\<\>\"\|]+(\\|\/){0,1})+$
Try this one for Windows and Linux support: ((?:[a-zA-Z]\:){0,1}(?:[\\/][\w.]+){1,})
I use this regex for capturing valid file/folder paths in windows (including UNCs and %variables%), with the exclusion of root paths like "C:\" or "\\serverName"
^(([a-zA-Z]:|\\\\\w[ \w\.]*)(\\\w[ \w\.]*|\\%[ \w\.]+%+)+|%[ \w\.]+%(\\\w[ \w\.]*|\\%[ \w\.]+%+)*)
this regex does not match leading spaces in path elements, so
"C:\program files" is matched
"C:\ pathWithLeadingSpace" is not matched
variables are allowed at any level
"%program files%" is matched
"C:\my path with inner spaces\%my var with inner spaces%" is matched
regex CmdPrompt("^([A-Z]:[^\<\>\:\"\|\?\*]+)");
Basically we look for everything that's not in the list of forbidden Windows Path Characters:
< (less than)
> (greater than)
: (colon)
" (double quote)
| (vertical bar or pipe)
? (question mark)
* (asterisk)
I know this is really old... but expanding on #agent-j's response I've added named groups, and support for period characters.
^(?<ParentPath>(?:[a-zA-Z]\:|\\\\[\w\s\.]+\\[\w\s\.$]+)\\(?:[\w\s\.]+\\)*)(?<BaseName>[\w\s\.]*?)$
I've saved this at Regexr
I found most of the answers here to be a little hit or miss.
Found a good solution here though:
https://social.msdn.microsoft.com/forums/vstudio/en-US/31d2bc84-c948-4914-8a9d-97b9e788b341/validate-a-network-folder-path
Note* - this is only for network shares - not local files
Answer:
string pattern = #"^\\{2}[\w-]+(\\{1}(([\w-][\w-\s]*[\w-]+[$$]?)|([\w-][$$]?$)))+";
string[] names = { #"\\my-network\somelocation", #"\\my-network\\somelocation",
#"\\\my-network\somelocation", #"my-network\somelocation",
#"\\my-network\\somelocation",#"\\my-network\somelocation\aa\dd",
#"\\my-network\somelocation\",#"\\my-network\\somelocation"};
foreach (string name in names)
{
if (Regex.IsMatch(name, pattern))
{
Console.WriteLine(name);
//Directory.Exists function to check if file exists
}
}
Alexander's Answer + Relative Paths
Alexander has the most correct answer thus far since it supports spaces in file names (i.e. C:\Program Files (x86)\ will match)... This aims to include relative paths as well.
For example, you can do cd / or cd \ and it does the same thing.
Further more, if you're currently in C:\some\path\to\some\place and you type either of those commands, you end up at C:\
Even more, you should consider paths, that start with '/' as a root path (to the current drive).
(?:[a-zA-Z]:(\|/)|file://|\\|.(/|\)|/)([^,\/:*\?\<>\"\|]+(\|/){0,1})
A Modified version of Alexander's answer, however, we include paths that are relative with no leading / or drive letter, as well as / with no leading drive letter (relative to the current drive as root).