Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

WNetGetConnection - Resolve a UNC Path

RSS
Modified on Mon, Feb 11, 2013, 2:57 PM by Administrator Categorized as Windows API
using System;
using System.Runtime.InteropServices;
using System.Text;

namespace UncConverter
{
    public static class FileInfo
    {
        [DllImport("mpr.dll")]
        static extern uint WNetGetConnection(string lpLocalName, StringBuilder lpRemoteName, ref int lpnLength);

        public static string ConvertToUnc(string fileName)
        {
            bool isLocal = true;  // assume local until disproved

            // strip trailing backslashes from fileName
            var driveName = fileName.Substring(0, 2);

            int length = 256; // to be on safe side 
            StringBuilder networkShare = new StringBuilder(length);
            uint status = WNetGetConnection(driveName, networkShare, ref length);

            // does a network share exist for this drive?
            if (networkShare.Length != 0)
            {
                // now networkShare contains a UNC path in format \\MachineName\ShareName
                // retrieve the MachineName portion
                String shareName = networkShare.ToString();
                string[] splitShares = shareName.Split('\\');
                // the 3rd array element now contains the machine name
                if (Environment.MachineName != splitShares[2])
                    fileName = shareName + fileName.Substring(2);
            }
            return fileName;
        }
    
    }
}

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2018, Patrick Jasinski.