What is the correct way to check if a path is an UNC path or a local path?

后端 未结 6 781
说谎
说谎 2020-12-15 04:09

The easiest way to check if a path is an UNC path is of course to check if the first character in the full path is a letter or backslash. Is this a good solution or could th

6条回答
  •  粉色の甜心
    2020-12-15 04:44

    The most accurate approach is going to be using some interop code from the shlwapi.dll

    [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
    [ResourceExposure(ResourceScope.None)]
    [return: MarshalAsAttribute(UnmanagedType.Bool)]
    internal static extern bool PathIsUNC([MarshalAsAttribute(UnmanagedType.LPWStr), In] string pszPath);
    

    You would then call it like this:

        /// 
        /// Determines if the string is a valid Universal Naming Convention (UNC)
        /// for a server and share path.
        /// 
        /// The path to be tested.
        ///  if the path is a valid UNC path; 
        /// otherwise, .
        public static bool IsUncPath(string path)
        {
            return PathIsUNC(path);
        }
    

    @JaredPar has the best answer using purely managed code.

提交回复
热议问题