关键字: VB 共享 创建 访问 作者:董含君
原来我发的帖子
http://search.csdn.net/Expert/topic/2440/2440801.xml?temp=6.267726E-03
在此感谢rainstormmaster,以及 动力港湾的帮助
整理一下
由于Win9x 跟 WinNT不一样,所以比较麻烦
最简单的设置共享的方法自然是shell 然后使用Net Share 以及 Net Use 来创建连接,最后使用控制台命令进行copy 以及 delete (举例copy \\192.168.5.11\d$\*.* d:\)
很简单的可以实现,包括WinAPI的open read ... 都支持这种访问方式.
本文对这种方法不做详细讨论(这个比较简单)
本文讨论的是如何利用纯代码以及API来实现共享的创建与访问.相关部分感兴趣的可以自己封装成类,下次调用的时候简单一些.
大体步骤:
1 建立共享
2 建立计算机之间的连接
3 枚举目录,读 写 等文件操作
4 关闭连接
1 如何设置共享
这是我引用别人的模块,(对不起,原作者的名字不是我删的,bas拿来时已经没有了)。
Option Explicit
'2000 下用API来实现目录共享及删除共享
'共享类型
Private Const STYPE_ALL As Long = -1
Private Const STYPE_DISKTREE As Long = 0
Private Const STYPE_PRINTQ As Long = 1
Private Const STYPE_DEVICE As Long = 2
Private Const STYPE_IPC As Long = 3
Private Const STYPE_SPECIAL As Long = &H80000000
'权限
Private Const ACCESS_READ As Long = &H1
Private Const ACCESS_WRITE As Long = &H2
Private Const ACCESS_CREATE As Long = &H4
Private Const ACCESS_EXEC As Long = &H8
Private Const ACCESS_DELETE As Long = &H10
Private Const ACCESS_ATRIB As Long = &H20
Private Const ACCESS_PERM As Long = &H40
Private Const ACCESS_ALL As Long = ACCESS_READ Or _
ACCESS_WRITE Or _
ACCESS_CREATE Or _
ACCESS_EXEC Or _
ACCESS_DELETE Or _
ACCESS_ATRIB Or _
ACCESS_PERM
'共享信息
Private Type SHARE_INFO_2
shi2_netname As Long '共享名
shi2_type As Long '类型
shi2_remark As Long '备注
shi2_permissions As Long '权限
shi2_max_uses As Long '最大用户
shi2_current_uses As Long '
shi2_path As Long '路径
shi2_passwd As Long '密码
End Type
'设置共享
Private Declare Function NetShareAdd Lib "netapi32" _
(ByVal ServerName As Long, _
ByVal level As Long, _
buf As Any, _
parmerr As Long) As Long
'删除共享
Private Declare Function NetShareDel Lib "netapi32.dll" _
(ByVal ServerName As Long, _
ByVal ShareName As Long, _
ByVal dword As Long) As Long
'设置共享(返回0 为成功)
'参数:
'sServer 计算机名
'sSharePath 要共享路径
'sShareName 显示的共享名
'sShareRemark 备注
'sSharePw 密码
Private Function ShareAdd(sServer As String, _
sSharePath As String, _
sShareName As String, _
sShareRemark As String, _
sSharePw As String) As Long
Dim lngServer As Long
Dim lngNetname As Long
Dim lngPath As Long
Dim lngRemark As Long
Dim lngPw As Long
Dim parmerr As Long
Dim si2 As SHARE_INFO_2
lngServer = StrPtr(sServer) '转成地址
lngNetname = StrPtr(sShareName)
lngPath = StrPtr(sSharePath)
'如果有备注信息
If Len(sShareRemark) > 0 Then
lngRemark = StrPtr(sShareRemark)
End If
'如果有密码
If Len(sSharePw) > 0 Then
lngPw = StrPtr(sSharePw)
End If
'初始化共享信息
With si2
.shi2_netname = lngNetname
.shi2_path = lngPath
.shi2_remark = lngRemark
.shi2_type = STYPE_DISKTREE
.shi2_permissions = ACCESS_ALL
.shi2_max_uses = -1
.shi2_passwd = lngPw
End With
'设置共享(用户名,共享类型,共享信息,)
ShareAdd = NetShareAdd(lngServer, _
2, _
si2, _
parmerr)
End Function
'删除共享(返回0 为成功)
'参数:
'sServer 计算机名
'sShareName 共享名
Private Function DelShare(sServer As String, _
sShareName As String) As Long
Dim lngServer As Long '计算机名
Dim lngNetname As Long '共享名
lngServer = StrPtr(sServer) '转成地址
lngNetname = StrPtr(sShareName)
'删除共享
DelShare = NetShareDel(lngServer, lngNetname, 0)
End Function
(感谢源代码提供者)
由于Win98与Win2000的不同,响应的代码也不一样.
以下是win9x的
在98下建立访问类型为完全的访问密码为“”的共享文件夹
Option Explicit
Private Const NERR_SUCCESS As Long = 0&
' Share types
Private Const STYPE_ALL As Long = -1 'note: my const
Private Const STYPE_DISKTREE As Long = 0
Private Const STYPE_PRINTQ As Long = 1
Private Const STYPE_DEVICE As Long = 2
Private Const STYPE_IPC As Long = 3
Private Const STYPE_SPECIAL As Long = &H80000000
' Flags
Private Const SHI50F_RDONLY = &H1
Private Const SHI50F_FULL = &H2
Private Const SHI50F_DEPENDSON = SHI50F_RDONLY + SHI50F_FULL
Private Const SHI50F_ACCESSMASK = SHI50F_RDONLY + SHI50F_FULL
Private Const SHI50F_PERSIST = &H100 ' Partage persistant
Private Const SHI50F_SYSTEM = &H200 ' Partage cach?
' Permissions (Win ME/NT/2000/XP)
Private Const ACCESS_READ As Long = &H1
Private Const ACCESS_WRITE As Long = &H2
Private Const ACCESS_CREATE As Long = &H4
Private Const ACCESS_EXEC As Long = &H8
Private Const ACCESS_DELETE As Long = &H10
Private Const ACCESS_ATRIB As Long = &H20
Private Const ACCESS_PERM As Long = &H40
Private Const ACCESS_ALL As Long = ACCESS_READ Or ACCESS_WRITE Or ACCESS_CREATE Or ACCESS_EXEC Or ACCESS_DELETE Or ACCESS_ATRIB Or ACCESS_PERM
' Win 9x
Private Type SHARE_INFO_50
shi50_netname(0 To 12) As Byte 'LM20_NNLEN + 1
shi50_type As Byte 'EShareType
shi50_flags As Integer
shi50_remark As Long
shi50_Path As Long
shi50_rw_password(0 To 8) As Byte 'SHPWLEN + 1
shi50_ro_password(0 To 8) As Byte 'SHPWLEN + 1
End Type
' Quelle systeme d'exploitation
Private Type OSVERSIONINFO
dwOSVersionInfoSize As Long
dwMajorVersion As Long
dwMinorVersion As Long
dwBuildNumber As Long
dwPlatformId As Long
szCSDVersion As String * 128
End Type
Private Declare Function NetShareAdd95 Lib "SVRAPI" Alias "NetShareAdd" (ByVal servername As String, ByVal level As Integer, ByVal buf As Long, ByVal cbBuffer As Integer) As Long
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (lpvDest As Any, lpvSource As Any, ByVal cbCopy As Long)
Private Sub cmdCreateShare_Click()
Dim lngSuccess As Long
' Create the share
'要添加上相应的textbox
lngSuccess = ShareAdd(UCase(txtComputerName.Text), UCase(txtLocalPath.Text), UCase(txtShareName.Text), txtShareDesc.Text)
'lngSuccess = ShareAdd(txtComputerName.Text, txtLocalPath.Text, txtShareName.Text, txtShareDesc.Text, txtSharePassRo.Text, txtSharePassRw.Text)
Select Case lngSuccess
Case 0: ' Share created successfully
Case 2118'共享名已经存在,就改改共享名,我这随便补了一个1
lngSuccess = ShareAdd(UCase(txtComputerName.Text), UCase(txtLocalPath.Text), UCase(txtShareName.Text) + "1", txtShareDesc.Text)
Case Else: MsgBox "Create error number " & lngSuccess, vbCritical, "Error"
End Select
End Sub
Private Function ShareAdd(sServer As String, sSharePath As String, sShareName As String, sShareRemark As String) As Long
Dim si50 As SHARE_INFO_50
Dim iErrParam As Integer
Dim lpszPath() As Byte
Dim lpszRemark() As Byte
Dim intFlags As Integer
intFlags = SHI50F_FULL Or SHI50F_PERSIST 'mode normal le partage est visible sur la machine
' flags = SHI50F_FULL Or SHI50F_PERSIST Or SHI50F_SYSTEM 'mode syst鑝e partage invisible
lpszPath = StrConv(sSharePath, vbFromUnicode) & vbNullChar
lpszRemark = StrConv(sShareRemark, vbFromUnicode) & vbNullChar
With si50
StrToByte sShareName, VarPtr(.shi50_netname(0))
.shi50_type = STYPE_DISKTREE
.shi50_remark = VarPtr(lpszRemark(0))
.shi50_Path = VarPtr(lpszPath(0))
StrToByte "", VarPtr(.shi50_ro_password(0))
StrToByte "", VarPtr(.shi50_rw_password(0))
.shi50_flags = intFlags
End With
ShareAdd = NetShareAdd95("", 50, ByVal VarPtr(si50), LenB(si50))
End Function
Private Sub StrToByte(strInput As String, ByVal lpByteArray As Long)
Dim lpszInput() As Byte
lpszInput = StrConv(strInput, vbFromUnicode) & vbNullChar
CopyMemory ByVal lpByteArray, lpszInput(0), UBound(lpszInput)
End Sub
2 连接远程共享
下一步就是连接
Windows对于共享的访问是这样的(记不清出了)
a 判断远程共享是否有密码(guest是否允许)
b 判断远程共享的密码是否与当前帐户一致,或者是否为空密码
c 用用户名密码连接,并且记录下来这个密码,方便以后使用
d 如果需要映射网络驱动器,那么映射一个盘符
可以利用Net use 命令,但是 win98跟win2000不一样,net use 也不一样
以下是代码实现
================
把下面代码放到module中
Option Explicit
Const WN_Success = &H0
Const WN_Not_Supported = &H1
Const WN_Net_Error = &H2
Const WN_Bad_Pointer = &H4
Const WN_Bad_NetName = &H32
Const WN_Bad_Password = &H6
Const WN_Bad_Localname = &H33
Const WN_Access_Denied = &H7
Const WN_Out_Of_Memory = &HB
Const WN_Already_Connected = &H34
Public ErrorNum As Long
Public ErrorMsg As String
Public rc As Long
Private Const ERROR_NO_CONNECTION = 8
Private Const ERROR_NO_DISCONNECT = 9
Private Type NETRESOURCE
dwScope As Long
dwType As Long
dwDisplayType As Long
dwUsage As Long
lpLocalName As String
lpRemoteName As String
lpComment As String
lpProvider As String
End Type
Private Declare Function WNetAddConnection2 Lib "mpr.dll" Alias "WNetAddConnection2A" (lpNetResource As NETRESOURCE, ByVal lpPassword As String, ByVal lpUserName As String, ByVal dwFlags As Long) As Long
Const NO_ERROR = 0
Const CONNECT_UPDATE_PROFILE = &H1
Const RESOURCETYPE_DISK = &H1
Const RESOURCETYPE_PRINT = &H2
Const RESOURCETYPE_ANY = &H0
Const RESOURCE_GLOBALNET = &H2
Const RESOURCEDISPLAYTYPE_SHARE = &H3
Const RESOURCEUSAGE_CONNECTABLE = &H1
Public Function ConnectUserPassword(sDrive As String, sService As String, Optional sUser As String = "", Optional sPassword As String = "") As Boolean
Dim NETR As NETRESOURCE
Dim errInfo As Long
With NETR
.dwScope = RESOURCE_GLOBALNET
.dwType = RESOURCETYPE_DISK
.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE
.dwUsage = RESOURCEUSAGE_CONNECTABLE
.lpRemoteName = sDrive
.lpLocalName = sService
End With
errInfo = WNetAddConnection2(NETR, sPassword, sUser, CONNECT_UPDATE_PROFILE)
ConnectUserPassword = errInfo = NO_ERROR
End Function
================
call ConnectUserPassword("\\servername", "", "password", "username")
相当于 net use \\servername password /user:username
3 文件操作
windows支持对 \\192.168.5.1\共享名\文件 的直接操作,很明显的,比如用API来操作
用FSO也是一样的.这个例子是利用FSO进行操作,跟本地没有什么两样.
//1列出sharedir的内容:
首先引用Microsoft Scripting Runtime
窗体上一个treeview,一个listbox:
Option Explicit
Dim FSO As New FileSystemObject
Private Sub Form_Load()
Dim mfolder As Folder
Set mfolder = FSO.GetFolder("\\192.168.2.1\guo")
Dim mnode As Node
Set mnode = Me.TreeView1.Nodes.Add(, , mfolder.Path, mfolder.Path)
Dim a As File
For Each a In mfolder.Files
Me.List1.AddItem a.Name
Next
Dim subfolder As Folder
For Each subfolder In mfolder.SubFolders
Me.TreeView1.Nodes.Add mnode, tvwChild, subfolder.Path, subfolder.Name
Next
Set subfolder = Nothing
Set a = Nothing
Set mfolder = Nothing
End Sub
Private Sub Form_Unload(Cancel As Integer)
Set FSO = Nothing
End Sub
Private Sub TreeView1_NodeClick(ByVal Node As MSComctlLib.Node)
On Error Resume Next
Dim mfolder As Folder
Set mfolder = FSO.GetFolder(Node.Key)
Dim a As File
List1.Clear
For Each a In mfolder.Files
Me.List1.AddItem a.Name
Next
Dim subfolder As Folder
For Each subfolder In mfolder.SubFolders
Me.TreeView1.Nodes.Add Node, tvwChild, subfolder.Path, subfolder.Name
Next
Set subfolder = Nothing
Set a = Nothing
Set mfolder = Nothing
End Sub
由于FSO有时会被管理员禁用(大多数病毒都是利用FSO),所以还要准备后手,一下是通用的办法.
就用现成的例子吧:
'Create a form with a command button (command1), a list box (list1)
'and four text boxes (text1, text2, text3 and text4).
'Type in the first textbox a startingpath like c:\(这里你输入共享文件夹的路径,如:
\\ns\mytest试试)
'and in the second textbox you put a pattern like *.* or *.txt
Private Declare Function FindFirstFile Lib "kernel32" Alias "FindFirstFileA" (ByVal lpFileName As String, lpFindFileData As WIN32_FIND_DATA) As Long
Private Declare Function FindNextFile Lib "kernel32" Alias "FindNextFileA" (ByVal hFindFile As Long, lpFindFileData As WIN32_FIND_DATA) As Long
Private Declare Function GetFileAttributes Lib "kernel32" Alias "GetFileAttributesA" (ByVal lpFileName As String) As Long
Private Declare Function FindClose Lib "kernel32" (ByVal hFindFile As Long) As Long
Const MAX_PATH = 260
Const MAXDWORD = &HFFFF
Const INVALID_HANDLE_VALUE = -1
Const FILE_ATTRIBUTE_ARCHIVE = &H20
Const FILE_ATTRIBUTE_DIRECTORY = &H10
Const FILE_ATTRIBUTE_HIDDEN = &H2
Const FILE_ATTRIBUTE_NORMAL = &H80
Const FILE_ATTRIBUTE_READONLY = &H1
Const FILE_ATTRIBUTE_SYSTEM = &H4
Const FILE_ATTRIBUTE_TEMPORARY = &H100
Private Type FILETIME
dwLowDateTime As Long
dwHighDateTime As Long
End Type
Private Type WIN32_FIND_DATA
dwFileAttributes As Long
ftCreationTime As FILETIME
ftLastAccessTime As FILETIME
ftLastWriteTime As FILETIME
nFileSizeHigh As Long
nFileSizeLow As Long
dwReserved0 As Long
dwReserved1 As Long
cFileName As String * MAX_PATH
cAlternate As String * 14
End Type
Function StripNulls(OriginalStr As String) As String
If (InStr(OriginalStr, Chr(0)) > 0) Then
OriginalStr = Left(OriginalStr, InStr(OriginalStr, Chr(0)) - 1)
End If
StripNulls = OriginalStr
End Function
Function FindFilesAPI(path As String, SearchStr As String, FileCount As Integer, DirCount As Integer)
'KPD-Team 1999
'E-Mail: KPDTeam@Allapi.net
Dim FileName As String ' Walking filename variable...
Dim DirName As String ' SubDirectory Name
Dim dirNames() As String ' Buffer for directory name entries
Dim nDir As Integer ' Number of directories in this path
Dim I As Integer ' For-loop counter...
Dim hSearch As Long ' Search Handle
Dim WFD As WIN32_FIND_DATA
Dim Cont As Integer
If Right(path, 1) <> "\" Then path = path & "\"
' Search for subdirectories.
nDir = 0
ReDim dirNames(nDir)
Cont = True
hSearch = FindFirstFile(path & "*", WFD)
If hSearch <> INVALID_HANDLE_VALUE Then
Do While Cont
DirName = StripNulls(WFD.cFileName)
' Ignore the current and encompassing directories.
If (DirName <> ".") And (DirName <> "..") Then
' Check for directory with bitwise comparison.
If GetFileAttributes(path & DirName) And FILE_ATTRIBUTE_DIRECTORY Then
dirNames(nDir) = DirName
DirCount = DirCount + 1
nDir = nDir + 1
ReDim Preserve dirNames(nDir)
End If
End If
Cont = FindNextFile(hSearch, WFD) 'Get next subdirectory.
Loop
Cont = FindClose(hSearch)
End If
' Walk through this directory and sum file sizes.
hSearch = FindFirstFile(path & SearchStr, WFD)
Cont = True
If hSearch <> INVALID_HANDLE_VALUE Then
While Cont
FileName = StripNulls(WFD.cFileName)
If (FileName <> ".") And (FileName <> "..") Then
FindFilesAPI = FindFilesAPI + (WFD.nFileSizeHigh * MAXDWORD) + WFD.nFileSizeLow
FileCount = FileCount + 1
List1.AddItem path & FileName
End If
Cont = FindNextFile(hSearch, WFD) ' Get next file
Wend
Cont = FindClose(hSearch)
End If
' If there are sub-directories...
If nDir > 0 Then
' Recursively walk into them...
For I = 0 To nDir - 1
FindFilesAPI = FindFilesAPI + FindFilesAPI(path & dirNames(I) & "\", SearchStr, FileCount, DirCount)
Next I
End If
End Function
Sub Command1_Click()
Dim SearchPath As String, FindStr As String
Dim FileSize As Long
Dim NumFiles As Integer, NumDirs As Integer
Screen.MousePointer = vbHourglass
List1.Clear
List1.Visible = False
SearchPath = Text1.Text
FindStr = Text2.Text
FileSize = FindFilesAPI(SearchPath, FindStr, NumFiles, NumDirs)
Text3.Text = NumFiles & " Files found in " & NumDirs + 1 & " Directories"
Text4.Text = "Size of files found under " & SearchPath & " = " & Format(FileSize, "#,###,###,##0") & " Bytes"
Screen.MousePointer = vbDefault
List1.Visible = True
End Sub
复制的例子
//2、复制sharedir下的文件到本地
//3、怎样才能实现像windows那样的进度控制
窗体上一个按钮,一个ProgressBar:Option Explicit
'\\192.168.2.1\guo\123.rar
Public Function CopyFile(Src As String, Dst As String, mProgressBar As ProgressBar) As Single
Dim BTest As Single, FSize As Single
Dim F1 As Integer, F2 As Integer
Dim sArray() As Byte
Dim buff As Integer
Const BUFSIZE = 1024
buff = 1024
F1 = FreeFile
Open Src For Binary Access Read As F1
F2 = FreeFile
Open Dst For Binary As F2
FSize = LOF(F1)
BTest = FSize - LOF(F2)
ReDim sArray(BUFSIZE) As Byte
Do
If BTest < BUFSIZE Then
buff = BTest
ReDim sArray(buff) As Byte
End If
Get F1, , sArray
Put F2, , sArray
BTest = FSize - LOF(F2)
If BTest < 0 Then
mProgressBar.Value = 100
Else
mProgressBar.Value = (100 - Int(100 * BTest / FSize))
End If
Loop Until BTest <= 0
Close F1
Close F2
CopyFile = FSize
End Function
Private Sub Command1_Click()
'复制文件 d:\ms\room.exe 到 d:\room1.exe
CopyFile "\\192.168.2.1\guo\123.rar", "d:\myroom2.exe", ProgressBar1
End Sub
需要指出的是以上代码成功运行的前提是共享文件夹的访问类型为“完全”,如果你的共享文件夹的访问类型为“只读”,你需要在程序运行时,改变它的访问类型为为“完全”。既然你已经知道了:
如何共享文件夹,这里我就不罗嗦了
其实,访问一个访问类型为“完全”的共享文件夹,和访问本地文件没有什么不同
4 断开连接
这个比较简单....有两种方法
'=============================================
Option Explicit
Private Const RESOURCETYPE_DISK = &H1
Private Const RESOURCETYPE_ANY = &H0
Private Const RESOURCETYPE_PRINT = &H2
Private Const RESOURCETYPE_UNKNOWN = &HFFFF
Private Declare Function WNetCancelConnection2 Lib "mpr.dll" Alias "WNetCancelConnection2A" (ByVal lpName As String, ByVal dwFlags As Long, ByVal fForce As Long) As Long
Private Declare Function WNetDisconnectDialog Lib "mpr.dll" (ByVal hWnd As Long, ByVal dwType As Long) As Long
Public Function DisconnectNetworkDialog() As Long
DisconnectNetworkDialog = WNetDisconnectDialog(0&, RESOURCETYPE_DISK)
End Function
Private Sub Command1_Click() '第一种方法
Call DisconnectNetworkDialog
End Sub
Private Sub Command2_Click()' 第二种方法
Call WNetCancelConnection2("\\10.0.0.1\temp", 1, True)
End Sub
总结:
现在可以说问题已经解决了
虽然还有一些小小的问题,比如列出文件列表时有时会溢出。这个我会自己想办法解决的
本来只想问一下如何连接的谁知道热心的rainstormmaster连98下的共享都列出来了。再次感谢rainstormmaster的帮助。
总结:
其实回过头来看看,这个问题的答案其实并不困难。是我想的太复杂了。没想到简单的FindFirstFile、FindNextFile解决了我的问题。还有远程文件的访问居然可以直接Open...
真是应了这句话:“没有做不到,只有想不到”
还有感谢 动力港湾 提供的mpr.dll的使用方法。原来只是映射网络驱动器,没有想到不用映射也可以建立连接。又是一个“没想到”。建议大家以后遇到问题时多多尝试一下。说不定就成功了呢 ^o^