Solved

Copying from a network share

Posted on 2017-04-17
3
44 Views
Last Modified: 2017-04-18
Hi Guys,

I'm looking for a way to copy files on a network share to a local folder. I'm now doing this via a mapped network connection, but as this sometimes times out I would like to do this in the software.

I've come across this piece of code:

Imports System.Runtime.InteropServices
Imports System.Net
Imports System.ComponentModel

Public Class NetworkConnection
    Implements IDisposable

    Private _networkName As String

    Public Sub New(networkName As String, credentials As NetworkCredential)
        _networkName = networkName

        Dim ntResource = New NetResource() With { _
            .Scope = ResourceScope.GlobalNetwork, _
            .ResourceType = ResourceType.Disk, _
            .DisplayType = ResourceDisplaytype.Share, _
            .RemoteName = networkName _
        }

        Dim userName = If(String.IsNullOrEmpty(credentials.Domain), credentials.UserName, String.Format("{0}\{1}", credentials.Domain, credentials.UserName))

        Dim result = WNetAddConnection2(ntResource, credentials.Password, userName, 0)

        If result <> 0 Then
            Throw New Win32Exception(result, "Error connecting to remote share")
        End If
    End Sub

    Public Sub Dispose() Implements IDisposable.Dispose
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub

    Protected Overrides Sub Finalize()
        Try
            Dispose(False)
        Finally
            MyBase.Finalize()
        End Try
    End Sub

    Protected Overridable Sub Dispose(disposing As Boolean)
        WNetCancelConnection2(_networkName, 0, True)
    End Sub

    <DllImport("mpr.dll")> _
    Private Shared Function WNetAddConnection2(netResource As NetResource, password As String, username As String, flags As Integer) As Integer
    End Function

    <DllImport("mpr.dll")> _
    Private Shared Function WNetCancelConnection2(name As String, flags As Integer, force As Boolean) As Integer
    End Function
End Class

<StructLayout(LayoutKind.Sequential)> _
Public Class NetResource
    Public Scope As ResourceScope
    Public ResourceType As ResourceType
    Public DisplayType As ResourceDisplaytype
    Public Usage As Integer
    Public LocalName As String
    Public RemoteName As String
    Public Comment As String
    Public Provider As String
End Class

Public Enum ResourceScope As Integer
    Connected = 1
    GlobalNetwork
    Remembered
    Recent
    Context
End Enum

Public Enum ResourceType As Integer
    Any = 0
    Disk = 1
    Print = 2
    Reserved = 8
End Enum

Public Enum ResourceDisplaytype As Integer
    Generic = &H0
    Domain = &H1
    Server = &H2
    Share = &H3
    File = &H4
    Group = &H5
    Network = &H6
    Root = &H7
    Shareadmin = &H8
    Directory = &H9
    Tree = &HA
    Ndscontainer = &HB
End Enum

Open in new window


Which is then used by a call like this (simplified):

        Dim cred As Net.NetworkCredential
        cred = New Net.NetworkCredential(*User*, *Pass)

        Try
            Using (New NetworkConnection(String.Format("\\{0}", *NetworkIP*), cred))
                IO.File.Copy(*RemoteFile*, *LocalFile*, true)
            End Using
        Catch ex as exception
            *Error handling*
        End try

Open in new window


This solution works great.... as long as now File Explorer windows are opened. As soon as an Explorer window is opened, authentication fails (even if the Explorer window hasn't even touched the remote PC).

Question: Is there a better way to do this (preferably) or is there a way to close all Explorer windows (without killing off the main Explorer.exe process)

Thanks!
0
Comment
Question by:mvdriel
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 31

Accepted Solution

by:
Shaun Vermaak earned 500 total points
ID: 42095336
I would impersonate and use File.Copy
Imports System.IO
Imports System.Security.Principal
...
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal)

Dim wid As WindowsIdentity = New WindowsIdentity("username", "password")
Dim context As WindowsImpersonationContext = wid.Impersonate()

File.Copy("\\192.168.0.1\Share$\test.txt", "C:\Temp\test.txt", True)

context.Undo()

Open in new window

0
 

Author Comment

by:mvdriel
ID: 42098179
Your solution didn't work out of the box (it gave me an "invalid username" error), but pointed me in the right direction. Impersonating is the way to go. Thanks!
0
 
LVL 31

Expert Comment

by:Shaun Vermaak
ID: 42098279
Glad we could help.

@OP, experts and future visitors:
Please remember to endorse my, or any other expert's comments that you found helpful by clicking on the "Thumb's Up" button

Read more on endorsements
https://www.experts-exchange.com/discussions/218503/What-are-Endorsements.html
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
Michael from AdRem Software outlines event notifications and Automatic Corrective Actions in network monitoring. Automatic Corrective Actions are scripts, which can automatically run upon discovery of a certain undesirable condition in your network.…
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…

687 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question