Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / C#
Article

Network Shares and UNC paths

Rate me:
Please Sign up or sign in to vote.
4.95/5 (59 votes)
11 Nov 2003CPOL3 min read 519.1K   8.9K   117   90
Classes to enumerate network shares on local and remote machines, and convert local file paths to UNC paths.

Introduction

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.

Implementation

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.

Classes

Share

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.

ShareCollection

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.

Demonstration

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.

C#
//
// 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) 
        {
            try 
            {
                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);

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

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

Updates

  • 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

Credits

This code is (very) loosely based on a VB6 solution by Karl E. Peterson [http://www.mvps.org/vb].

License

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


Written By
Software Developer CodeProject
United Kingdom United Kingdom
I started writing code when I was 8, with my trusty ZX Spectrum and a subscription to "Input" magazine. Spent many a happy hour in the school's computer labs with the BBC Micros and our two DOS PCs.

After a brief detour into the world of Maths, I found my way back into programming during my degree via free copies of Delphi and Visual C++ given away with computing magazines.

I went straight from my degree into my first programming job, at Trinet Ltd. Eleven years later, the company merged to become ArcomIT. Three years after that, our project manager left to set up Nevalee Business Solutions, and took me with him. Since then, we've taken on four more members of staff, and more work than you can shake a stick at. Smile | :)

Between writing custom code to integrate with Visma Business, developing web portals to streamline operations for a large multi-national customer, and maintaining RedAtlas, our general aviation airport management system, there's certainly never a dull day in the office!

Outside of work, I enjoy real ale and decent books, and when I get the chance I "tinkle the ivories" on my Technics organ.

Comments and Discussions

 
AnswerRe: How to get sub dirs? Pin
Richard Deeming25-May-04 6:02
mveRichard Deeming25-May-04 6:02 
GeneralRe: How to get sub dirs? Pin
jmacduff25-May-04 6:46
jmacduff25-May-04 6:46 
QuestionNetwork Shares in VB.NET? Pin
sa4720k22-Jan-04 4:34
sa4720k22-Jan-04 4:34 
AnswerRe: Network Shares in VB.NET? Pin
Heath Stewart24-Jun-04 6:35
protectorHeath Stewart24-Jun-04 6:35 
GeneralRe: Network Shares in VB.NET? Pin
sa4720k24-Jun-04 9:46
sa4720k24-Jun-04 9:46 
GeneralRe: Network Shares in VB.NET? Pin
Heath Stewart24-Jun-04 9:51
protectorHeath Stewart24-Jun-04 9:51 
QuestionHow to create a file in a password-protected shared network folder? Pin
12-Jan-04 23:18
suss12-Jan-04 23:18 
AnswerRe: How to create a file in a password-protected shared network folder? Pin
C.G.Betta9-Mar-04 12:26
C.G.Betta9-Mar-04 12:26 
GeneralRe: How to create a file in a password-protected shared network folder? Pin
zcaccau30-Apr-04 6:37
zcaccau30-Apr-04 6:37 
GeneralGenghis -- Shares, Maps, etc... Pin
Member 86052861-Dec-03 5:21
Member 86052861-Dec-03 5:21 
GeneralEnumerate network Pin
totig12-Nov-03 4:52
totig12-Nov-03 4:52 
GeneralRe: Enumerate network Pin
Richard Deeming12-Nov-03 4:56
mveRichard Deeming12-Nov-03 4:56 
GeneralException Pin
Anthony_Yio9-Nov-03 23:04
Anthony_Yio9-Nov-03 23:04 
GeneralRe: Exception Pin
Richard Deeming9-Nov-03 23:20
mveRichard Deeming9-Nov-03 23:20 
GeneralRe: Exception Pin
Anthony_Yio9-Nov-03 23:55
Anthony_Yio9-Nov-03 23:55 
QuestionHow to *create* a network share..... Pin
kmansari29-Oct-03 11:34
kmansari29-Oct-03 11:34 
AnswerRe: How to *create* a network share..... Pin
Richard Deeming30-Oct-03 2:49
mveRichard Deeming30-Oct-03 2:49 
GeneralRe: How to *create* a network share..... Pin
mogadanez17-Jul-05 23:51
mogadanez17-Jul-05 23:51 
GeneralInteresting question... Pin
Richard Deeming24-Oct-03 7:10
mveRichard Deeming24-Oct-03 7:10 
GeneralRe: Interesting question...ASP.NET PatToUNC Pin
maximius13-Nov-03 1:45
maximius13-Nov-03 1:45 
GeneralBug Pin
bearskin3-Oct-03 9:04
bearskin3-Oct-03 9:04 
GeneralRe: Bug Pin
Richard Deeming5-Oct-03 23:45
mveRichard Deeming5-Oct-03 23:45 
GeneralRe: Bug Pin
bearskin6-Oct-03 3:03
bearskin6-Oct-03 3:03 
GeneralRe: Bug Pin
bearskin6-Oct-03 3:06
bearskin6-Oct-03 3:06 
GeneralRe: Bug Pin
Richard Deeming6-Oct-03 3:29
mveRichard Deeming6-Oct-03 3:29 

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.