Check if the full path is specified

Is there a way to check if a given path is a complete path? I'm doing this right now:

if (template.Contains(":\\")) //full path already given { } else //calculate the path from local assembly { } 

But should there be a more elegant way to test this?

+97
c # validation path
Apr 6 2018-11-11T00:
source share
8 answers

Try using System.IO.Path.IsPathRooted ? It also returns true for absolute paths.

 System.IO.Path.IsPathRooted(@"c:\foo"); // true System.IO.Path.IsPathRooted(@"\foo"); // true System.IO.Path.IsPathRooted("foo"); // false System.IO.Path.IsPathRooted(@"c:1\foo"); // surprisingly also true System.IO.Path.GetFullPath(@"c:1\foo");// returns "[current working directory]\1\foo" 
+130
Apr 6 2018-11-11T00:
source share
— -
 Path.IsPathRooted(path) && !Path.GetPathRoot(path).Equals(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal) 

Above condition:

  • does not require file system permissions
  • returns false in most cases when the path format is invalid (and does not throw an exception)
  • returns true only if path turns on the volume

In scenarios like the one given by the OP, it may be more appropriate than the conditions in the previous answers. Unlike the above condition:

  • path == System.IO.Path.GetFullPath(path) throws exceptions rather than returning false in the following scenarios:
    • The caller does not have the required permissions
    • The system failed to get the absolute path.
    • the path contains a colon (":"), which is not part of the volume identifier
    • The specified path, file name, or both exceed the maximum length specified by the system
  • System.IO.Path.IsPathRooted(path) returns true if path starts with a single directory separator.

Finally, here is a method that wraps the above condition, and also eliminates the remaining possible exceptions:

 public static bool IsFullPath(string path) { return !String.IsNullOrWhiteSpace(path) && path.IndexOfAny(System.IO.Path.GetInvalidPathChars().ToArray()) == -1 && Path.IsPathRooted(path) && !Path.GetPathRoot(path).Equals(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal); } 

UPDATE: EM0 made a good comment and an alternative answer , addressing a curious case of paths such as C: and C:dir . To decide how you can handle such paths, you can dive deep into MSDN → Windows desktop applications → Development → Desktop technologies → Data access and storage → Local file systems - → File management → About file management → Creating, deleting and maintaining Files → Naming Files, Paths , and Namespaces → Fully Qualified and Relative Paths

For Windows API functions that manipulate files, file names can often be relative to the current directory, while some APIs require a fully qualified path. A file name relative to the current directory, if it does not start with one of the following:

  • A UNC name of any format that always starts with two backslash characters ("\"). See the next section for more information.
  • The backslash drive designation, for example, "C: \" or "d: \".
  • The only backslash, for example, "\ directory" or "\ file.txt". This is also called the absolute path.

If the file name begins only with the drive designation, and not with a backslash after the colon, this is interpreted as the relative path to the current directory on the drive with the specified letter. Please note that the current directory may or may not be the root directory, depending on what it was installed during the most recent "directory change" operation on this disk. Examples of this format:

  • "C: tmp.txt" refers to a file named "tmp.txt" in the current directory on drive C.
  • "C: tempdir \ tmp.txt" refers to a file in a subdirectory of the current directory on drive C.

[...]

+26
Jan 27 '16 at 19:34
source share

Try

 System.IO.Path.IsPathRooted(template) 

Works for both UNC paths and local paths.

eg.

 Path.IsPathRooted(@"\\MyServer\MyShare\MyDirectory") // returns true Path.IsPathRooted(@"C:\\MyDirectory") // returns true 
+15
Apr 6 2018-11-11T00:
source share

Old question, but another applicable answer. If you need to make sure that the volume is included in the local path, you can use System.IO.Path.GetFullPath () as follows:

 if (template == System.IO.Path.GetFullPath(template)) { ; //template is full path including volume or full UNC path } else { if (useCurrentPathAndVolume) template = System.IO.Path.GetFullPath(template); else template = Assembly.GetExecutingAssembly().Location } 
+12
Sep 19 '15 at 12:34
source share

Based on weir's answer: it does not generate invalid paths, but also returns false for paths such as "C:", "C: dirname" and "\ path".

 public static bool IsFullPath(string path) { if (string.IsNullOrWhiteSpace(path) || path.IndexOfAny(Path.GetInvalidPathChars()) != -1 || !Path.IsPathRooted(path)) return false; string pathRoot = Path.GetPathRoot(path); if (pathRoot.Length <= 2 && pathRoot != "/") // Accepts X:\ and \\UNC\PATH, rejects empty string, \ and X:, but accepts / to support Linux return false; if (pathRoot[0] != '\\' || pathRoot[1] != '\\') return true; // Rooted and not a UNC path return pathRoot.Trim('\\').IndexOf('\\') != -1; // A UNC server name without a share name (eg "\\NAME" or "\\NAME\") is invalid } 

Note that this returns different results on Windows and Linux, for example, "/ path" is absolute on Linux, but not on Windows.

Unit test:

 [Test] public void IsFullPath() { bool isWindows = Environment.OSVersion.Platform.ToString().StartsWith("Win"); // .NET Framework // bool isWindows = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows); // .NET Core // These are full paths on Windows, but not on Linux TryIsFullPath(@"C:\dir\file.ext", isWindows); TryIsFullPath(@"C:\dir\", isWindows); TryIsFullPath(@"C:\dir", isWindows); TryIsFullPath(@"C:\", isWindows); TryIsFullPath(@"\\unc\share\dir\file.ext", isWindows); TryIsFullPath(@"\\unc\share", isWindows); // These are full paths on Linux, but not on Windows TryIsFullPath(@"/some/file", !isWindows); TryIsFullPath(@"/dir", !isWindows); TryIsFullPath(@"/", !isWindows); // Not full paths on either Windows or Linux TryIsFullPath(@"file.ext", false); TryIsFullPath(@"dir\file.ext", false); TryIsFullPath(@"\dir\file.ext", false); TryIsFullPath(@"C:", false); TryIsFullPath(@"C:dir\file.ext", false); TryIsFullPath(@"\dir", false); // An "absolute", but not "full" path // Invalid on both Windows and Linux TryIsFullPath(null, false, false); TryIsFullPath("", false, false); TryIsFullPath(" ", false, false); TryIsFullPath(@"C:\inval|d", false, false); TryIsFullPath(@"\\is_this_a_dir_or_a_hostname", false, false); TryIsFullPath(@"\\is_this_a_dir_or_a_hostname\", false, !isWindows); TryIsFullPath(@"\\is_this_a_dir_or_a_hostname\\", false, !isWindows); } private static void TryIsFullPath(string path, bool expectedIsFull, bool expectedIsValid = true) { Assert.AreEqual(expectedIsFull, PathUtils.IsFullPath(path), "IsFullPath('" + path + "')"); if (expectedIsFull) { Assert.AreEqual(path, Path.GetFullPath(path)); } else if (expectedIsValid) { Assert.AreNotEqual(path, Path.GetFullPath(path)); } else { Assert.That(() => Path.GetFullPath(path), Throws.Exception); } } 
+9
Nov 30 '17 at 9:24
source share

To check if the path is fully qualified (MSDN) :

 public static bool IsPathFullyQualified(string path) { var root = Path.GetPathRoot(path); return root.StartsWith(@"\\") || root.EndsWith(@"\"); } 

This is slightly simpler than what has already been suggested, and still returns false for disk-related paths such as C:foo . Its logic is directly based on the definition of MSDN "fully qualified", and I did not find a single example on which he would behave badly.




Interestingly, .NET Core 2.1 seems to have introduced a new Path.IsPathFullyQualified method, which uses the internal PathInternal.IsPartiallyQualified method (the location of the link is accurate as of 2018-04-17).

For posterity and better self-sufficiency of this post, here is the latest implementation for reference:

 internal static bool IsPartiallyQualified(ReadOnlySpan<char> path) { if (path.Length < 2) { // It isn't fixed, it must be relative. There is no way to specify a fixed // path with one character (or less). return true; } if (IsDirectorySeparator(path[0])) { // There is no valid way to specify a relative path with two initial slashes or // \? as ? isn't valid for drive relative paths and \??\ is equivalent to \\?\ return !(path[1] == '?' || IsDirectorySeparator(path[1])); } // The only way to specify a fixed path that does not begin with two slashes // is the drive, colon, slash format- ie C:\ return !((path.Length >= 3) && (path[1] == VolumeSeparatorChar) && IsDirectorySeparator(path[2]) // To match old behavior we'll check the drive character for validity as the path is technically // not qualified if you don't have a valid drive. "=:\" is the "=" file default data stream. && IsValidDriveChar(path[0])); } 
+6
Apr 17 '18 at 16:47
source share

This is the solution I am using

 public static bool IsFullPath(string path) { try { return Path.GetFullPath(path) == path; } catch { return false; } } 

This works as follows:

 IsFullPath(@"c:\foo"); // true IsFullPath(@"C:\foo"); // true IsFullPath(@"c:\foo\"); // true IsFullPath(@"c:/foo"); // false IsFullPath(@"\foo"); // false IsFullPath(@"foo"); // false IsFullPath(@"c:1\foo\"); // false 
+2
Apr 11 '18 at 12:49
source share

I'm not quite sure what you mean by the full path (although it is assumed that from the example you mean not relative from the root onwards), well, you can use Path to help you work with the physical paths of the file system, which should cover you in most cases.

0
Apr 6 2018-11-11T00:
source share



All Articles