Jasinski Technical Wiki


Home Page
All Pages

Quick Search
Advanced Search »

Contributor Links

Create a new Page
File Management
Your Profile

Other Wiki Sections



WNetGetConnection - Resolve a UNC Path

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
        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 Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2023, Patrick Jasinski.