[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x
?
Solved

Accessing a File Share which requires a Username/Password

Posted on 2010-09-16
9
Medium Priority
?
1,377 Views
Last Modified: 2012-05-10
Hello,

I'm writing some code that needs to access a networked fileshare that requires a username and password. No domains involved.

My code is below but i'm getting the following error.

I've done a google and it talks about impersonating a user, but I've tried and cant get my head round it. What I need is some code that easily shows where to put the username and password in so that I can authentice with the network share.

Thanks
Dan

Error below:-

System.IO.IOException: Logon failure: unknown user name or bad password.

   at System.IO.__Error.WinIOError(Int32 errorCode, String str)
   at System.IO.Directory.InternalGetFileDirectoryNames(String fullPath, String userPath, Boolean file)
   at System.IO.Directory.InternalGetFiles(String path, String userPath, String searchPattern)
   at System.IO.DirectoryInfo.GetFiles(String searchPattern)
   at NumberAssigner.clsRecordingsSyncroniser.RunningCode() in D:\HostingSpaces\admin\keshercall.com\NumberAssigner\clsRecordingsSyncroniser.vb:line 35
Dim dirRecordings As New DirectoryInfo("\\sip2\Recordings\recordings\")
                Dim f As FileInfo

                For Each f In dirRecordings.GetFiles("*.txt")
                    If File.Exists("\\sip2\Recordings\recordings\" & Left(f.Name, Len(f.Name) - Len(f.Exists)) & ".wav") Then

                    End If
                Next

Open in new window

0
Comment
Question by:DanJourno
[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
  • 5
  • 4
9 Comments
 
LVL 29

Expert Comment

by:nffvrxqgrcfqvvc
ID: 33694021
You will need to use WNetAddConnection2 P/Invoke.
0
 
LVL 5

Author Comment

by:DanJourno
ID: 33694088
Do you have a code sample?
0
 
LVL 29

Expert Comment

by:nffvrxqgrcfqvvc
ID: 33694124
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 5

Author Comment

by:DanJourno
ID: 33695282
Do I have to map the network share to a drive letter using this method?
0
 
LVL 29

Accepted Solution

by:
nffvrxqgrcfqvvc earned 2000 total points
ID: 33695360
Nope. You just pass "Nothing" for local name...
Here is an example

Imports System.Runtime.InteropServices
Imports System.ComponentModel
 
Public Class Form1
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            ' To add resource without drive.
            WNet.AddConnection("user", "password", "\\192.168.1.100\shared", Nothing)
            ' To close that connection
            'WNet.CancelConnection("\\192.168.1.100\shared")
        Catch ex As Win32Exception
            Debug.Print("code={0} message={1}", ex.NativeErrorCode, ex.Message)
        End Try
    End Sub
End Class

Public Class WNet
    Private Const NO_ERROR As Integer = 0

    Private Enum WNetType As Integer
        RESOURCETYPE_ANY
        RESOURCETYPE_DISK
        RESOURCETYPE_PRINT
        RESOURCETYPE_RESERVED
    End Enum

    <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> _
    Private Structure NETRESOURCE
        Dim dwScope As Integer
        Dim dwType As Integer
        Dim dwDisplayType As Integer
        Dim dwUsage As Integer
        Dim lpLocalName As String
        Dim lpRemoteName As String
        Dim lpComment As String
        Dim lpProvider As String
    End Structure

    <DllImport("mpr.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
    Private Shared Function WNetAddConnection2(ByRef lpNetResource As NETRESOURCE, ByVal lpPassword As String, ByVal lpUsername As String, ByVal dwFlags As Integer) As Integer
    End Function

    <DllImport("mpr.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
    Private Shared Function WNetCancelConnection2(ByVal lpName As String, ByVal dwFlags As Integer, ByVal fForce As Integer) As Integer
    End Function

    Public Shared Sub AddConnection(ByVal userName As String, ByVal password As String, ByVal remoteName As String, ByVal localName As String)
        Dim nr As NETRESOURCE = Nothing
        Dim dwResult As Integer = NO_ERROR
        nr.lpRemoteName = remoteName
        nr.lpLocalName = localName
        nr.dwType = WNetType.RESOURCETYPE_ANY
        dwResult = WNetAddConnection2(nr, password, userName, 0)
        If dwResult <> NO_ERROR Then
            Throw New Win32Exception(Marshal.GetLastWin32Error)
        End If
    End Sub

    Public Shared Sub CancelConnection(ByVal szName As String)
        Dim dwResult As Integer = NO_ERROR
        dwResult = WNetCancelConnection2(szName, 0, 1)
        If dwResult <> NO_ERROR Then
            Throw New Win32Exception(Marshal.GetLastWin32Error)
        End If
    End Sub

End Class

Open in new window

0
 
LVL 5

Author Comment

by:DanJourno
ID: 33695563
Hi egl1044,

I'm trying the code from your last post but i'm getting the following error.
I've tested the remote path using Windows Explorer and its correct.

"System.ComponentModel.Win32Exception: A specified logon session does not exist. It may already have been terminated
   at NumberAssigner.WNet.AddConnection(String userName, String password, String remoteName, String localName) in D:\HostingSpaces\admin\project\NumberAssigner\WNet.vb:line 42
   at NumberAssigner.clsRecordingsSyncroniser.RunningCode() in D:\HostingSpaces\admin\project\NumberAssigner\clsRecordingsSyncroniser.vb:line 33"
0
 
LVL 29

Expert Comment

by:nffvrxqgrcfqvvc
ID: 33699765
It's working fine for me, How are you providing information into AddConnection() can we see it?
0
 
LVL 5

Author Comment

by:DanJourno
ID: 33717819
All I'm doing is this:-

WNet.AddConnection("username", "password", "\\server3.mycompany.com\AsteriskRecordings", nothing)

also tried:-

WNet.AddConnection("username", "password", "\\server3.mycompany.com\AsteriskRecordings", "s:")

I can browse to the location using windows explorer without any problems.
I would map the drive, but ive had problems before if the remote server restarts, the mapped drive stops working until I open it again in Windows Explorer.
0
 
LVL 5

Author Comment

by:DanJourno
ID: 33721517
Just tried the exact same code again and now its working.

Stange.

Thanks.
0

Featured Post

Ask an Anonymous Question!

Don't feel intimidated by what you don't know. Ask your question anonymously. It's easy! Learn more and upgrade.

Question has a verified solution.

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

Article by: jpaulino
XML Literals are a great way to handle XML files and the community doesn’t use it as much as it should.  An XML Literal is like a String (http://msdn.microsoft.com/en-us/library/system.string.aspx) Literal, only instead of starting and ending with w…
Microsoft Reports are based on a report definition, which is an XML file that describes data and layout for the report, with a different extension. You can create a client-side report definition language (*.rdlc) file with Visual Studio, and build g…
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
Suggested Courses

656 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