Click here to Skip to main content
11,934,214 members (36,092 online)
Click here to Skip to main content
Add your own
alternative version


109 bookmarked

Network Shares and UNC paths

, 11 Nov 2003 CPOL
Rate this:
Please Sign up or sign in to vote.
Classes to enumerate network shares on local and remote machines, and convert local file paths to UNC paths.


Two common requirements seem to have been missed from the .NET framework: enumerating network shares, and converting a local path to a UNC path. The shares could potentially be retrieved via WMI, but you can't guarantee that NT4 and 98 will have it installed. These classes provide a simple wrapper around the API calls necessary to retrieve this information.


To retrieve the UNC path for a file on a mapped drive, call WNetGetUniversalName. This doesn't work on Windows 95, but neither does the .NET framework, so I don't care!

If the path is on a local shared folder, WNetGetUniversalName won't help. In this case, you need to call NetShareEnum and look for a matching path. The function behaves completely differently across NT/2K/XP and 9x/ME, so there are two versions of this code.

  • In the NT version, you may not have permissions to access the SHARE_INFO_2 information, so the code will revert to the SHARE_INFO_1 structure. In this case, the path will not be available.
  • On Windows 9x/ME/NT4, the server name (if any) must be prefixed with "\\". The code will check this, so you don't need to worry.
  • On Windows 9x/ME, there is no way to resume the enumeration, so the code will return a maximum of 20 shares.



Encapsulates information about a single network share, including the server name, share name, share type, local path and comment. Also has some utility methods to determine if it is a file-system share, whether it matches part of a local path, and returns the root directory.


A strongly-typed read-only collection of Share objects. Shares can be retrieved by index or by path, in which case the best match will be returned. Includes factory methods to return the shares for a specified computer, and static methods to return the UNC path and local share for a local path.

Interesting Note

The Windows 98 structure SHARE_INFO_50 is declared in the file SrvApi.h. Towards the top of the file, there is a line which reads #pragma pack(1). Although this looks like complete gobbledegook, it is actually important. The number in brackets specifies the packing for all structures in the file. According to MSDN, the alignment of a member will be on a boundary that is either a multiple of n or a multiple of the size of the member, whichever is smaller.

In the case of the SHARE_INFO_50 structure, the default packing, pads the structure to align the members on 8 byte boundaries. This meant that the size was calculated as 44 bytes, when it should be 42. Two extra padding bytes are added to the end of the structure to make the length a multiple of 4, the size of the native integer.

After tearing my hair out trying to work out why the size was wrong, and why taking two bytes off the end reduced the size by four bytes, I finally noticed the Pack property of the StructLayoutAttribute class. Adding Pack=1 to the attribute fixed the problems, and the code now works on Windows 98.


The testShares.cs file contains a sample console application which demonstrates the main functionality. The testShares.exe file is the compiled version of this sample.

// Enumerate shares on local computer
Console.WriteLine("\nShares on local computer:");
ShareCollection shi = ShareCollection.LocalShares;
if (shi != null) 
    foreach(Share si in shi) 
        Console.WriteLine("{0}: {1} [{2}]", 
            si.ShareType, si, si.Path);

        // If this is a file-system share, try to
        // list the first five subfolders.
        // NB: If the share is on a removable device,
        // you could get "Not ready" or "Access denied"
        // exceptions.
        if (si.IsFileSystem) 
                System.IO.DirectoryInfo d = si.Root;
                System.IO.DirectoryInfo[] Flds = d.GetDirectories();
                for (int i=0; i < Flds.Length && i < 5; i++)
                    Console.WriteLine("\t{0} - {1}", i, Flds[i].FullName);

            catch (Exception ex) 
                Console.WriteLine("\tError listing {0}:\n\t{1}\n", 
                    si, ex.Message);
    Console.WriteLine("Unable to enumerate the local shares.");

// Resolve local paths to UNC paths.
Console.WriteLine("{0} = {1}", 
    fileName, ShareCollection.PathToUnc(fileName));


  • 25 September 2002 - Original Release
  • 13 March 2003 -
    • Changed the ShareCollection to inherit from System.Collections.ReadOnlyCollection.
    • Moved the P/Invoke code inside the ShareCollection class, and removed the internal Interop class.
    • Fixed the packing bug on Windows 9x. Note to self: When the C++ header file says #pragma pack(1), don't ignore it!
    • Added support for level 1 share enumeration on Windows 98, which is required to list shares on remote machines, but isn't documented in MSDN.
  • 12 November 2003 - Bug fix


This code is (very) loosely based on a VB6 solution by Karl E. Peterson [].


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Richard Deeming
Software Developer Nevalee Business Solutions
United Kingdom United Kingdom
No Biography provided

You may also be interested in...

Comments and Discussions

QuestionCode doesnot work in 64 Bit Applications Pin
Winfried Wille25-Mar-14 7:08
professionalWinfried Wille25-Mar-14 7:08 
AnswerRe: Code doesnot work in 64 Bit Applications Pin
Richard Deeming25-Mar-14 7:25
professionalRichard Deeming25-Mar-14 7:25 
GeneralRe: Code doesnot work in 64 Bit Applications Pin
Winfried Wille25-Mar-14 7:37
professionalWinfried Wille25-Mar-14 7:37 
QuestionExe works but source does not Pin
davidcole2-Feb-14 11:06
memberdavidcole2-Feb-14 11:06 
AnswerRe: Exe works but source does not Pin
Richard Deeming3-Feb-14 2:52
professionalRichard Deeming3-Feb-14 2:52 
GeneralMy vote of 5 Pin
Midax20-Sep-13 9:53
memberMidax20-Sep-13 9:53 
GeneralMy vote of 5 Pin
EdsonF00076-Sep-13 6:27
memberEdsonF00076-Sep-13 6:27 
GeneralMy vote of 5 Pin
John Simmons / outlaw programmer17-Nov-12 11:44
mvpJohn Simmons / outlaw programmer17-Nov-12 11:44 
GeneralMy vote of 5 Pin
Romulus-Tours28-Feb-11 6:14
memberRomulus-Tours28-Feb-11 6:14 
GeneralFail of ShareCollection.GetShares(""); and ShareCollection.GetShares(@"\\"); in Vista Pin
Josep Maria Roy7-Jan-10 4:59
memberJosep Maria Roy7-Jan-10 4:59 
GeneralRe: Fail of ShareCollection.GetShares(""); and ShareCollection.GetShares(@"\\"); in Vista Pin
Richard Deeming7-Jan-10 5:32
memberRichard Deeming7-Jan-10 5:32 
Questionsam thing in java?? Pin
gaurav_nanda21-Mar-08 5:50
membergaurav_nanda21-Mar-08 5:50 
GeneralLicence issues ... UNC classes Pin
vin kerai18-Dec-07 16:42
membervin kerai18-Dec-07 16:42 
GeneralRe: Licence issues ... UNC classes Pin
ThunderWeasel26-Jul-11 8:54
memberThunderWeasel26-Jul-11 8:54 
GeneralFunctionality is too robust for needs Pin
vachaun19-Apr-07 9:45
membervachaun19-Apr-07 9:45 
GeneralRe: Functionality is too robust for needs Pin
Richard Deeming19-Apr-07 9:52
memberRichard Deeming19-Apr-07 9:52 
GeneralRe: Functionality is too robust for needs Pin
vachaun19-Apr-07 10:17
membervachaun19-Apr-07 10:17 
QuestionAccessDenied flag wrong? Pin
Toby_9-Mar-07 3:36
memberToby_9-Mar-07 3:36 
AnswerRe: AccessDenied flag wrong? Pin
Richard Deeming9-Mar-07 3:45
memberRichard Deeming9-Mar-07 3:45 
GeneralRe: AccessDenied flag wrong? Pin
Toby_12-Mar-07 1:58
memberToby_12-Mar-07 1:58 
QuestionHow to retrive Shared Files(not folder) using WMI Pin
i_razi23-Feb-07 10:56
memberi_razi23-Feb-07 10:56 
AnswerRe: How to retrive Shared Files(not folder) using WMI Pin
Richard Deeming26-Feb-07 4:32
memberRichard Deeming26-Feb-07 4:32 
GeneralRe: How to retrive Shared Files(not folder) using WMI Pin
i_razi26-Feb-07 10:53
memberi_razi26-Feb-07 10:53 
GeneralWTF [modified] Pin
lexodus22-Feb-07 22:34
memberlexodus22-Feb-07 22:34 
GeneralRe: WTF Pin
Richard Deeming23-Feb-07 1:31
memberRichard Deeming23-Feb-07 1:31 
GeneralRe: WTF Pin
lexodus23-Feb-07 4:30
memberlexodus23-Feb-07 4:30 
Uh, oh.

First; It wasnt my opinion to attack you, if i did this, sorry for that! I will change my comment to a not be that excessive. (Or kill it complete).

I was relating to the following code;
/// Share information level 1, Win9x
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack=1)]
protected struct SHARE_INFO_1_9x
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=13)]
public string NetName;
public byte Padding;
public ushort bShareType;

public string Remark;

public ShareType ShareType
get { return (ShareType)((int)bShareType & 0x7FFF); }

There are some little things which could be done in a other way;

1. the type UShort ist not CLS compliance. I marked it as internal and tested it on Windows2000 case with all members as internal, works fine. --> There is no warranty that every .NET language can handle this type properly. (Visual Basic .NET for example)

2. There is no need to cast "bShareType & 0x7FFF" to an int and then cast it to ShareType (as i know an enum derives from int if you dont specify a other type).
I would advise you a plugin such as Resharper for VS2003, because the naked VS2003IDE is crap. (This plugin tells you that you have redundant Type casts) and does codeanalysis without starting the debugger. And it has a billion other cool features.

My code looks as follows (and all other Structs).

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack=1)]
protected struct SHARE_INFO_1_9x
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=13)]
public string NetName;
public byte Padding;
internal ushort bShareType;

public string Remark;
public ShareType ShareType
get { return (ShareType)(bShareType & 0x7FFF); }

As you see, the code hasnt got many changes (my previous comment had to be a joke... it was a bad (joke sorry)).

GeneralThanks a lot! Pin
lexodus22-Feb-07 6:42
memberlexodus22-Feb-07 6:42 
GeneralRe: Thanks a lot! Pin
mrjmwcom3-Apr-07 8:53
membermrjmwcom3-Apr-07 8:53 
GeneralBug with IsValidFilePath Pin
Monkeyget226-Jan-07 5:35
memberMonkeyget226-Jan-07 5:35 
GeneralRe: Bug with IsValidFilePath Pin
Richard Deeming26-Jan-07 5:46
memberRichard Deeming26-Jan-07 5:46 
QuestionShow file list under UNC path Pin
jhtang22-Jan-07 10:18
memberjhtang22-Jan-07 10:18 
AnswerRe: Show file list under UNC path Pin
Richard Deeming26-Jan-07 5:55
memberRichard Deeming26-Jan-07 5:55 
QuestionASP.NET Pin
neongenesis197513-Aug-06 21:57
memberneongenesis197513-Aug-06 21:57 
AnswerRe: ASP.NET Pin
Richard Deeming14-Aug-06 1:39
memberRichard Deeming14-Aug-06 1:39 
GeneralGreat wrapper. Pin
Slackshot29-Jun-06 12:04
memberSlackshot29-Jun-06 12:04 
GeneralRe: Great wrapper. Pin
itamar8212-Aug-08 23:02
memberitamar8212-Aug-08 23:02 
GeneralRe: Great wrapper. Pin
colin.newell224-May-09 9:29
membercolin.newell224-May-09 9:29 
Generalcopy files from local computer to the remote computer using WMI Pin
arunpnet20-Apr-06 22:00
memberarunpnet20-Apr-06 22:00 
GeneralRe: copy files from local computer to the remote computer using WMI Pin
rajukvrk7822-Jan-07 9:14
memberrajukvrk7822-Jan-07 9:14 
GeneralPlease help me! Pin
Anonymous16-Apr-05 7:51
sussAnonymous16-Apr-05 7:51 
GeneralNetShareEnum returns 2351 error code Pin
_Saper_2-Mar-05 3:05
member_Saper_2-Mar-05 3:05 
GeneralRe: NetShareEnum returns 2351 error code Pin
Richard Deeming2-Mar-05 10:14
memberRichard Deeming2-Mar-05 10:14 
GeneralRe: NetShareEnum returns 2351 error code Pin
_Saper_2-Mar-05 20:22
member_Saper_2-Mar-05 20:22 
GeneralError Code 50 Pin
Anonymous17-Feb-05 3:46
sussAnonymous17-Feb-05 3:46 
GeneralRemove a network share Pin
cjk007009-Jul-04 13:23
membercjk007009-Jul-04 13:23 
GeneralRe: Remove a network share Pin
aejw10-Mar-07 20:00
memberaejw10-Mar-07 20:00 
GeneralShares on a Server /Network Pin
Anonymous8-Jul-04 14:19
sussAnonymous8-Jul-04 14:19 
QuestionHow to get sub dirs? Pin
jmacduff21-May-04 7:13
memberjmacduff21-May-04 7:13 
AnswerRe: How to get sub dirs? Pin
Richard Deeming25-May-04 7:02
memberRichard Deeming25-May-04 7:02 
GeneralRe: How to get sub dirs? Pin
jmacduff25-May-04 7:46
memberjmacduff25-May-04 7:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.151126.1 | Last Updated 12 Nov 2003
Article Copyright 2002 by Richard Deeming
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid