我可以以编程方式在文件共享上执行“net use”吗?

时间:2009-09-08 17:33:52

标签: .net windows security filesystems impersonation

在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 

这有意义吗?

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

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

1 个答案:

答案 0 :(得分: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