|
|
Comments and Discussions
|
|
 |

|
Brilliant code and exactly what I needed. My only change was to make the ShareCollection a List<Share> so I could remove shares that were found that I wasn't interested in (default shares, non-disk shares, and stuff like that.
I'm using your code in my media center manager software to control where the user can search for media. Since the path is stored in a database that can be accessed from any PC on the LAN, I need to force the user to select from available UNC paths. Your code helps find the shares after I've found all the machines on the LAN.
Great stuff.
|
|
|
|
|

|
Hi,
good article! congratulations.
Just I'm using it from my web app with Framework 3.5 and Vista and I'm getting this errors:
ShareCollection shi = ShareCollection.GetShares("computer_name"); = works fine: 8 shared resources!
ShareCollection shi = ShareCollection.GetShares("10.0.255.13"); = fail
ShareCollection shi = ShareCollection.GetShares(@"\\10.0.255.13"); = fail
computer_name has 10.0.255.13 ip
The issue is in this lines:
nRet = NetShareEnum(server, level, out pBuffer, -1,
out entriesRead, out totalEntries, ref hResume);
if (ERROR_ACCESS_DENIED == nRet)
{
//Need admin for level 2, drop to level 1
level = 1;
nRet = NetShareEnum(server, level, out pBuffer, -1,
out entriesRead, out totalEntries, ref hResume);
}
in 2nd nRet = NetShareEnum, nRet is still returning ERROR_ACCESS_DENIED. I have tested in some computers of my network and my conclusion is when you are using IP NetShareEnum seems that is not working fine in Vista (not tested neither XP nor Windows 7).
Talking of Windows 7: is this class compatible?
Yours sincerely,
Josep Balague
|
|
|
|

|
Strange - it works for me with either the computer name or IP address, from a console app or a web app. (I'm running Windows 7, so I guess that answers your last question.)
The documentation[^] says it requires "the DNS or NetBIOS name of the remote server", but the IP address (without the "\\" prefix) also seems to work.
Have you tried using WMI / System.Management[^]? A "Select * From Win32_Share[^]" query should return the list of shares.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|

|
hey !! can u suggest me how can i do same job in java???
its very important,,, please any one
|
|
|
|

|
Hi,
Can anyone please advise of any licence issues with regards to using these classes.
Regards
ViN.
|
|
|
|

|
This might be about 3 years too late, but you can find the licensing information here[^]. (There is a link at the top of the current page as well.)
Mark
|
|
|
|

|
This works fine, but it retrieves too much data for what I need. Is there a way to get only the items that would be listed if you browsed to the location using the UNC path of the server...
IE: Start -> Run -> \\server_name -> enter
and list only items that are shown here.
|
|
|
|

|
You can filter out any Share instances where the IsFileSystem property is false, which will leave you with the file-system shares.
If you want to hide the administrative shares as well, you can filter out any items where the ShareType property is equal to ShareType.Special.
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
|
|
|
|

|
That's exactly what I needed, with just a bit more fine tuning it gave me exactly what I wanted. Great Code!!!
|
|
|
|

|
First of all I want to thank you very much for this great peace of code! You saved me much work.
In the method EnumerateSharesNT(), however, I suppose there's a small bug regarding the accessDenied flag:
nRet = NetShareEnum(server, level, out pBuffer, -1,
out entriesRead, out totalEntries, ref hResume);
if (ERROR_ACCESS_DENIED == nRet)
{
level = 1;
nRet = NetShareEnum(server, level, out pBuffer, -1,
out entriesRead, out totalEntries, ref hResume);
accessDenied = true;
}
In my case the first NetShareEnum() call with level 2 returned ERROR_ACCESS_DENIED, then it correctly dropped to level 1 and called NetShareEnum() anew, which resulted in nRet == NO_ERROR. Nevertheless, accessDenied is set to true.
So I'd propose to write the following instead:
nRet = NetShareEnum(server, level, out pBuffer, -1,
out entriesRead, out totalEntries, ref hResume);
if (ERROR_ACCESS_DENIED == nRet)
{
level = 1;
nRet = NetShareEnum(server, level, out pBuffer, -1,
out entriesRead, out totalEntries, ref hResume);
if (ERROR_ACCESS_DENIED == nRet)
accessDenied = true;
}
Toby
|
|
|
|

|
I'm not sure what code you're looking at - there isn't a variable or field called accessDenied anywhere in the source.
The entire EnumerateSharesNT method reads:
protected static void EnumerateSharesNT(string server, ShareCollection shares)
{
int level = 2;
int entriesRead, totalEntries, nRet, hResume = 0;
IntPtr pBuffer = IntPtr.Zero;
try
{
nRet = NetShareEnum(server, level, out pBuffer, -1,
out entriesRead, out totalEntries, ref hResume);
if (ERROR_ACCESS_DENIED == nRet)
{
level = 1;
nRet = NetShareEnum(server, level, out pBuffer, -1,
out entriesRead, out totalEntries, ref hResume);
}
if (NO_ERROR == nRet && entriesRead > 0)
{
Type t = (2 == level) ? typeof(SHARE_INFO_2) : typeof(SHARE_INFO_1);
int offset = Marshal.SizeOf(t);
for (int i=0, lpItem=pBuffer.ToInt32(); i<entriesRead; i++, lpItem+=offset)
{
IntPtr pItem = new IntPtr(lpItem);
if (1 == level)
{
SHARE_INFO_1 si = (SHARE_INFO_1)Marshal.PtrToStructure(pItem, t);
shares.Add(si.NetName, string.Empty, si.ShareType, si.Remark);
}
else
{
SHARE_INFO_2 si = (SHARE_INFO_2)Marshal.PtrToStructure(pItem, t);
shares.Add(si.NetName, si.Path, si.ShareType, si.Remark);
}
}
}
}
finally
{
if (IntPtr.Zero != pBuffer)
NetApiBufferFree(pBuffer);
}
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
|
|
|
|

|
Oops, I'm sorry, I used the code from the Network Browsing Control, which itself uses your code, but slightly adapted. I didn't realize that the sources differ in exactly that flag.
|
|
|
|

|
I had searched a lot but unable to get help on reading shared Open Files using WMI. Please help on this. I can retrive till folder using this sample code. But this one is not working for Shared Files. I would like to read Computer Managemnt-Shared Folder-Open Files
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT *
FROM Win32_ConnectionShare");
foreach (ManagementObject connectionShare in searcher.Get())
{
// Win32_Share
string antecedent = connectionShare["Antecedent"].ToString();
Console.WriteLine("Antecedent: " + antecedent);
ManagementObject share = new ManagementObject(antecedent);
// Win32_ServerConnection
string dependant = connectionShare["Dependent"].ToString();
Console.WriteLine("Dependant: " + dependant);
ManagementObject connection = new ManagementObject(dependant);
Console.WriteLine(share["Name"].ToString());
if (connection != null && connection["Name"] != null)
Console.WriteLine(connection["Name"].ToString());
Console.WriteLine("\n");
}
adfg
|
|
|
|
|

|
Thanks a lot. We can achieve same by using either of two functions:
Private Sub FillOpenFile()
Dim objServerObject
Dim objresource
Dim lvData(2) As String
Dim lvItem As ListViewItem
InitializeListViewOpenFiles()
'Try
objServerObject = GetObject("WinNT://" & strOpenFileServer & "/LanmanServer")
If (IsNothing(objServerObject) = False) Then
For Each objresource In objServerObject.resources
If (Not objresource.User = "") Then
Dim strUser As String
strUser = objresource.User
strUser = strUser.Substring(strUser.Length - 1)
If (Not objresource.User = "") And (Not strUser = "$") Then
lvData(0) = objresource.name
lvData(1) = objresource.path
lvData(2) = objresource.user
On Error Resume Next
lvItem = New ListViewItem(lvData, 0)
lvwOpenFiles.Items.Add(lvItem)
End If
End If
Next
End If
'Catch ex As Exception
' 'MessageBox.Show(ex.Message)
'End Try
End Sub
'this also do the same as above-Iqubal
Private Sub FillOpenFile1()
Dim p As New Process
Dim pi As New ProcessStartInfo
pi.UseShellExecute = False
pi.RedirectStandardOutput = True
pi.Arguments = " /query /S " & strOpenFileServer & " /U AdminId /P !My!Password"
pi.WorkingDirectory = "C:\\windows\\system32"
'this for nt* computers
pi.FileName = "openfiles "
p.StartInfo = pi
p.StartInfo = pi
p.Start()
Dim sr As IO.StreamReader = p.StandardOutput
Dim sb As New System.Text.StringBuilder("")
Dim input As Integer = sr.Read
Do Until input = -1
sb.Append(ChrW(input))
input = sr.Read
Loop
MessageBox.Show(sb.ToString)
End Sub
adfg
|
|
|
|

|
The functionality is really good.
But there are some little changes you could do in relation to redundant Type Casts and CLS-Compliance.
@Edit; First post was much to excessive
|
|
|
|

|
Well then, oh mighty coding genius, how would you have written this structure?
The Win9x version is defined as:
typedef struct _share_info_1 {
char shi1_netname[LM20_NNLEN+1];
char shi1_pad1;
unsigned short shi1_type;
char FAR* shi1_remark;
} _share_info_1;
The WinNT version is defined as:
typedef struct _SHARE_INFO_1 {
LPWSTR shi1_netname;
DWORD shi1_type;
LPWSTR shi1_remark;
}
If you're so clever, let's see you do better.
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
|
|
|
|

|
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;
[MarshalAs(UnmanagedType.LPTStr)]
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)
http://dotnet.mvps.org/dotnet/articles/integeroperators/
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;
[MarshalAs(UnmanagedType.LPTStr)]
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)).
Greetings
|
|
|
|

|
You are a genious, thank you for this perfect piece of source-code!
You just safed my life.
Where to donate @?
|
|
|
|

|
I want to say thank you too!! I hope there are no problems with it. I really just needed to convert a path to a unc path...
You were right on when you said "Two common requirements seem to have been missed from the .NET framework"
|
|
|
|

|
I think there is a bug in the IsValidFilePath method. If the fileName is of length 1 or 2 it may throw an exception.
The precondition should check for such length instead of checking only for a length of zero.
|
|
|
|

|
Well spotted.
Line 524 should be changed to read:
if (null == fileName || 3 > fileName.Length) return false;
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
|
|
|
|

|
I try to show file information under UNC path on my web application, but I get " no network path was found." message.
Would you help me on this issue? Thank you very much.
DirectoryInfo CurrentRoot = new DirectoryInfo(@"\\servername\userdirectory") ;
FileSystemInfo[] files = CurrentRoot.GetFileSystemInfos() ;
FileSystemInfosExtend FileInfosEx = new FileSystemInfosExtend(files) ;
jtang
|
|
|
|

|
If the servername and share exist, the most likely problem is that the ASP.NET application doesn't have permission to access the share. You either need to grant the user account access, or make ASP.NET impersonate an account which does have access.
http://support.microsoft.com/kb/891031/[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
|
|
|
|
 |
|
|
General News Suggestion Question Bug Answer Joke Rant Admin
|
Classes to enumerate network shares on local and remote machines, and convert local file paths to UNC paths.
| Type | Article |
| Licence | CPOL |
| First Posted | 24 Sep 2002 |
| Views | 291,267 |
| Bookmarked | 104 times |
|
|