1

在 VB.NET 程序中,我想从文件系统读取文件,然后使用不同的凭据将这些文件的压缩版本写入远程、安全的文件共享。

cmd提示符下的类似操作是:

net use s: \\server\share /user:foo P@ssw0rd
copy a+b | compress > s:\foo.bin
net use s: /delete

这可能吗?如何?(不用担心压缩和文件 i/o。我的兴趣是安全部分。)

我这样做WindowsImpersonationContext吗?

编辑:你说得对,我真的不想映射驱动器;我想要做的是使用不是默认凭据的凭据访问共享。该应用程序由各种用户运行,并且他们通常没有对共享的写入权限。仅出于此单个文件的目的,我想允许用户写入共享。

那么如何使用替代凭据将单个文件写入共享?请记住,我需要默认凭据或身份来读取充当压缩输入的文件。

 UserX reads files a1 and b1 as UserX, writes file c1 as UserA 
 UserY reads files a2 and b2 as UserY, writes file c2 as UserA 

这有意义吗?

我知道我可以直接在共享上创建文件。问题是如何使用替代凭据来做到这一点?我知道在创建共享时如何传递替代凭据,这就是我介绍创建共享的想法的原因。我真的不需要共享,因为它仅针对单个文件完成,并且仅在程序中完成。

而且我知道我可以先创建文件,然后将文件复制到共享中。我不想这样做,因为它是一个大文件,我想流式传输一次。

4

1 回答 1

2

您不需要映射驱动器。您可以直接创建文件 \\server\share\foo.bin。

但是,如果你真的想要,这里有一些代码:

来自http://www.mredkj.com/vbnet/vbnetmapdrive.html

     Public Declare Function WNetAddConnection2 Lib "mpr.dll" Alias "WNetAddConnection2A" _
( ByRef lpNetResource As NETRESOURCE, ByVal lpPassword As String, _
ByVal lpUserName As String, ByVal dwFlags As Integer) As Integer

     Public Declare Function WNetCancelConnection2 Lib "mpr" Alias "WNetCancelConnection2A" _
(ByVal lpName As String, ByVal dwFlags As Integer, ByVal fForce As Integer) As Integer

        <StructLayout(LayoutKind.Sequential)> _
    Public Structure NETRESOURCE
            Public dwScope As Integer
            Public dwType As Integer
            Public dwDisplayType As Integer
            Public dwUsage As Integer
            Public lpLocalName As String
            Public lpRemoteName As String
            Public lpComment As String
            Public lpProvider As String
        End Structure

    Public Const ForceDisconnect As Integer = 1
    Public Const RESOURCETYPE_DISK As Long = &H1

    Public Function MapDrive(ByVal DriveLetter As String, ByVal UNCPath As String) As Boolean

            Dim nr As NETRESOURCE
            Dim strUsername As String
            Dim strPassword As String

            nr = New NETRESOURCE
            nr.lpRemoteName = UNCPath
            nr.lpLocalName = DriveLetter & ":"
            strUsername = Nothing '(add parameters to pass this if necessary)
            strPassword = Nothing '(add parameters to pass this if necessary)
            nr.dwType = RESOURCETYPE_DISK

            Dim result As Integer
            result = WNetAddConnection2(nr, strPassword, strUsername, 0)

            If result = 0 Then
                Return True
            Else
                Return False
            End If
        End Function

    Public Function UnMapDrive(ByVal DriveLetter As String) As Boolean
        Dim rc As Integer
            rc = WNetCancelConnection2(DriveLetter & ":", 0, ForceDisconnect)

            If rc = 0 Then
                Return True
            Else
                Return False
            End If

        End Function
于 2009-09-08T17:38:02.443 回答