none
Access to remote folder RRS feed

  • Question

  • Hi,

    I have an app which must read, change and save (update) files on remote PC.

    I have a special user/password to access the remote computer.

    Is there any way to loging to remote computer from inside the app, do the job and then log off.

    App works fine if I logging to remote PC before starting nut I don't like this. I'd like to have evrething hidden from enduser.

     

    Thanks

    Oleg

    Tuesday, August 29, 2006 5:11 PM

Answers

  • I was actually experimenting with this now.

    make sure that the share has the appropriate user account added into the permissions, then try this code:

     



    NetworkCredential theNetworkCredential = new NetworkCredential(username, password, domain);
    CredentialCache theNetcache = new CredentialCache();
    theNetCache.Add(@"\\computer", theNetworkCredential, "Basic", theNetworkCredential);
    //then do whatever, such as getting a list of folders:
    string[] theFolders = System.IO.Directory.GetDirectories("@\\computer\share");

     

    Tuesday, August 29, 2006 8:27 PM
    Moderator
  • if its on the local network then yes, otherwise if its on the internet somewhere, then you may need to connect via FTP using the FTP classes in .NET 2.0 or some other way, perhaps by webservice or something.

    To access to the remote computer on a local network, you need to set up the credentials (username/password) then access the network share, the credential class lives in the System.Net namespace, by the class name of "NetworkCredential".

    Supply it a username/password and a domain for example, and then access the remote share on the same network.

    You may also need to take a look at the System.Net.CredentialCache also

    Tuesday, August 29, 2006 6:01 PM
    Moderator

All replies

  • if its on the local network then yes, otherwise if its on the internet somewhere, then you may need to connect via FTP using the FTP classes in .NET 2.0 or some other way, perhaps by webservice or something.

    To access to the remote computer on a local network, you need to set up the credentials (username/password) then access the network share, the credential class lives in the System.Net namespace, by the class name of "NetworkCredential".

    Supply it a username/password and a domain for example, and then access the remote share on the same network.

    You may also need to take a look at the System.Net.CredentialCache also

    Tuesday, August 29, 2006 6:01 PM
    Moderator
  • Thanks for reply,

    You wrote: "Supply it a username/password and a domain for example, and then access the remote share on the same network."

    And there is a question: How I could apply my new NetworkCredential ?

    I don't see any way to let application know that I have credebtial.

    I use the generic file IO not FTP or HTTP access (remote server does not have IIS).

    Thanks

    Tuesday, August 29, 2006 8:15 PM
  • I was actually experimenting with this now.

    make sure that the share has the appropriate user account added into the permissions, then try this code:

     



    NetworkCredential theNetworkCredential = new NetworkCredential(username, password, domain);
    CredentialCache theNetcache = new CredentialCache();
    theNetCache.Add(@"\\computer", theNetworkCredential, "Basic", theNetworkCredential);
    //then do whatever, such as getting a list of folders:
    string[] theFolders = System.IO.Directory.GetDirectories("@\\computer\share");

     

    Tuesday, August 29, 2006 8:27 PM
    Moderator
  • just to add, you could also probably set the default credentials:

    CredentialCache.DefaultNetworkCredentials.Domain = domain;

    CredentialCache.DefaultNetworkCredentials.Username = username;

    CredentialCache.DefaultNetworkCredentials.Password = password;

     

    Although I haven't tried it, give it a shot and see what happens and if it works for you.

    Tuesday, August 29, 2006 8:41 PM
    Moderator
  • Hello again,

    Unfortunately the solution listed in previous messages does not work and there is no problem in user/password or any other security issues. I call "net use ..." from the same method passing the same values and successfully mapped to share folder.

    I found one solution which works, but it looks overcomplicated especially because of v 2.0:

    http://support.microsoft.com/default.aspx?scid=kb;EN-US;q306158

    If there is another way using managed code only?

    Thanks,

    Oleg

    Wednesday, August 30, 2006 2:32 PM
  • the link you provided is for ASP.NET.

    I'll see what else I can dig up. for now, as you suggested, are you able to use net use and map the drive, also giving the username/password in the net use command?

    Wednesday, August 30, 2006 2:39 PM
    Moderator
  •  ahmedilyas wrote:

    are you able to use net use and map the drive, also giving the username/password in the net use command?

    Yes,  I can map shared folder using use command.

    Friday, September 1, 2006 6:28 PM
  • Hi,

          I have the same problem.  I can "net use" to the file share using a user name and password.  But I can't do it using .NET code:

     

              NetworkCredential ncred = new NetworkCredential("administrator", "admin_pwd", "mymachine");
                CredentialCache ncache =  new CredentialCache();
                ncache.Add(new Uri(@"\\mymachine"), "Basic", ncred);

              try
                {
                    Directory.CreateDirectory(@\\mymachine\myshare);
                }
                catch (Exception ex)
                {
                    return;
                }

     

    Any help?

     

    Thanks!

    Friday, May 11, 2007 11:33 PM
  • Though  a whole lot of looking about, I found a solution to this.  You'll need to use Impersonate().

    using System.IO;  
    using System.Security.Permissions;  
    using System.Security.Principal;  
    using System.Runtime.InteropServices;  
     
    public partial class Form1 : Form  
    {  
      [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]  
      public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);  
     
      private void workToDo(object sender, EventArgs e)  
      {  
        IntPtr tokenHandle = new IntPtr(0);  
        tokenHandle = IntPtr.Zero;  
     
        bool returnValue = LogonUser(<userName>, <domain>, <password>, 2, 0, ref tokenHandle);  
        WindowsIdentity ImpersonatedIdentity = new WindowsIdentity(tokenHandle);  
        WindowsImpersonationContext MyImpersonation = ImpersonatedIdentity.Impersonate();  
              
    //Do whatever you want to do as this identity - directory.exists, directory.createdirectory, etc.  
     
        MyImpersonation.Undo();  
      }  
    }  
     

    Basically, you look up the user Token, then use that as your identity.  Just be sure to undo the identity when you're done using it (dont know what consequences there are, but I'm sure they're bad).

    Hope this helps someone!
    • Proposed as answer by Atohanie Friday, December 12, 2008 11:01 PM
    Friday, December 12, 2008 11:00 PM
  • 2 corrections to marked answers:

    1. Use 2 parameter constructor to create NetworkCredentials object.

    NetworkCredential theNetworkCredential = new NetworkCredential(@"domain\username", "password");
    

    One may think that 3 parameter constructor and 2 paramter constructor are equivalent, but practically they are not. Basic authentication seems to use only UserName and Password properties from NetworkCredential object.

    2. Correct syntax to add network credentials is as follows (not like one given by ahmedilyas).

    theNetCache.Add(new Uri(@\\computer), "Basic", theNetworkCredential);

    With these 2 changes I could access a remote share that was accessible only over VPN.

    PS: Answer on this forum is much elegant than answers on StackOverflow, which use native Win32 API.


    ~Zendu

    • Proposed as answer by zendu Thursday, March 13, 2014 12:29 PM
    Thursday, March 13, 2014 12:28 PM
  • Thank You! This works.

    Thursday, October 2, 2014 3:43 PM
  • //Access the shared on different network doesn't work

    NetworkCredential theNetworkCredential = new NetworkCredential(".\Admin", "password");

     CredentialCache theNetCache = new CredentialCache();
     theNetCache.Add(new Uri(@"\\124.32.322\d$\"), "Basic", theNetworkCredential);

    string[] theFolders = System.IO.Directory.GetDirectories(@"\\124.32.322\d$\");

    Error: UserName and Password is incorrect.

    I manually access the shared with same username/password  and it worked from windows run command: \\124.32.322\d$\



    • Edited by AnhD Friday, May 1, 2015 1:53 AM
    Friday, May 1, 2015 1:51 AM
  • With these changes to ahmedilyas answer this worked perfect.  I agree it is a much better answer that the one on Stackoverflow!

    Thanks to both of you!

    • Edited by Glenn Wright Sunday, September 13, 2015 12:15 PM
    Sunday, September 13, 2015 12:14 PM
  • Tring all the methods posted here, the only one that has worked to me is the one on:

    https://ericwijaya.wordpress.com/2013/02/06/access-remote-file-share-with-username-and-password-in-c/

    Using networkcredential and credentialcache not working to me.

    The link posted is working. I've used three different unc paths with the same user, password and domain and it's working perfectly.

    The only thing is that are is using an API that registers the path without letter in windows. Using in a cmd

    net use

    it shows the registered unc paths.

    • Proposed as answer by david develop Wednesday, June 7, 2017 8:21 AM
    Friday, June 2, 2017 9:03 AM
  • Those example were posted long time ago where they are still supporting "basic" authentication (i.e.: send username and password as plain text). For now you should pass "NTLM", "Digest", "Kerberos", or "Negotiate" instead. 

    Btw, in that WordPress article, if you pass the drive letter (say, "E:") you want to "useinfo.ui2_local", you can map the drive name in that function.



    Friday, June 2, 2017 9:28 AM
    Answerer
  • Hello, I'm using that function to "pass user and password to unc path"

     Private Sub PonCredenciales(ByVal pRutaFicheroCredenciales As String, ByVal pRuta As String)
            Dim lUsuario As String = String.Empty
            Dim lContraseña As String = String.Empty
            Dim lDominio As String = String.Empty
            Dim lNetWorkCredential As System.Net.NetworkCredential
    
            LeeCredencialesFichero(pRutaFicheroCredenciales, lUsuario, lContraseña, lDominio)
            If mListnetworkCredentials Is Nothing Then
                mListnetworkCredentials = New System.Collections.Generic.List(Of System.Net.NetworkCredential)
            End If
            lNetWorkCredential = New System.Net.NetworkCredential(lUsuario, lContraseña, lDominio)
            mListnetworkCredentials.Add(lNetWorkCredential)
            If mCredentialCache Is Nothing Then
                mCredentialCache = New System.Net.CredentialCache()
            End If
            mCredentialCache.Add(New Uri(pRuta), "Negotiate", lNetWorkCredential)
            EscribeMensajeLogLine("Leido fichero '" & pRutaFicheroCredenciales & "'")
            EscribeMensajeLogLine("Aplicadas credenciales a directorio '" & pRuta &
                                  "' con usuario=xxxxx , contraseña=xxxx y dominio=xxx")
            'EscribeMensajeLogLine("Aplicadas credenciales a directorio '" & pRuta &
            '"' con usuario=" & lUsuario & " y contraseña=" & lContraseña)
        End Sub

    But is not working

    I'm doing something wrong?

    Regards,

    Friday, June 2, 2017 9:51 AM
  • I can run the following code successfully. Maybe you should check whether your company's support staff hardened the system by limiting the choice of authentication method with group/local policy?

    Private Sub PonCredenciales(ByVal pRutaFicheroCredenciales As String, ByVal pRuta As String)
            Dim lUsuario As String = "<masked>"
            Dim lContraseña As String = "<masked>"
            Dim lDominio As String = "<masked>" ' use "." for local accounts here
            Dim lNetWorkCredential As System.Net.NetworkCredential
            Dim mListnetworkCredentials As New List(Of System.Net.NetworkCredential)
            Dim mCredentialCache As New System.Net.CredentialCache()
    
            'LeeCredencialesFichero(pRutaFicheroCredenciales, lUsuario, lContraseña, lDominio)
            lNetWorkCredential = New System.Net.NetworkCredential(lUsuario, lContraseña, lDominio)
            mListnetworkCredentials.Add(lNetWorkCredential)
            mCredentialCache.Add(New Uri(pRuta), "Negotiate", lNetWorkCredential)
            Console.WriteLine("Leido fichero '" & pRutaFicheroCredenciales & "'")
            Console.WriteLine("Aplicadas credenciales a directorio '" & pRuta &
                                  "' con usuario=xxxxx , contraseña=xxxx y dominio=xxx")
            'EscribeMensajeLogLine("Aplicadas credenciales a directorio '" & pRuta &
            '"' con usuario=" & lUsuario & " y contraseña=" & lContraseña)
            Dim theFolders As String() = System.IO.Directory.GetDirectories(pRuta)
    
        End Sub



    Friday, June 2, 2017 10:18 AM
    Answerer
  • Hello,

    I've tried with "NTLM", "Digest", "Kerberos", and "Negotiate" .

    No one works.

    The problem may be that the program is executed in a windows 2008 r2 server with no domain joined.

    To access to that unc path (\\computer\share) you have to use a username, password and a Domain.

    That user validates in a Domain.

    May be it has to be used another function or add more code.

    Regards,

    Friday, June 2, 2017 11:54 AM
  • That will not work for sure. To use domain account to access network share, both machine must join to the same domain, or a domain with cross domain trust. Without joining the domain, your machine won't have the "shared key" to decrypt the ticket. The password stored in CredentialCache won't do any good to you.

    In the case you specified, the things that will work is to properly use NetUseAdd() NetAPI, or to use a local account instead.

    • Proposed as answer by david develop Wednesday, June 7, 2017 8:21 AM
    Saturday, June 3, 2017 6:58 AM
    Answerer
  • Hello,

    thank you for your time and for the answer.

    I've found an url

    https://www.codeproject.com/Articles/608447/Directory-Authentication-for-Cross-Domain-Users-in

    that seems to validate to a domain. Validating in the domain using the routine in that url, will it work?

    Thanks,

    Tuesday, June 6, 2017 8:01 AM
  • It's for requested user information of a different domain.

    As long as it's not the LanmanRedirector of your current session get authenticated for the remote machine, you can't access the file share.


    Tuesday, June 6, 2017 1:44 PM
    Answerer
  • I realize the thread is a bit dated but hoping someone may have worked through this issue I'm seeing and have some insight to share.   

    Using the code suggested here, everything appears to be working as expected until I attempt to File.Move().  The error I get is "Access to the path '\\123.12.34.56\AS400\FILE\SHARE' is denied."

    If I change from an IP to a DNS name I get a different error: "The specified account does not exist."

    If I do a Net Use with either method it works with the same account from the same server.  The reason I need to move away from Net Use is to ensure using NTLMv2 or higher.

    I tried with various authType values:  Basic, Digest, NTLM, Kerberos, & Negotiate but get similar errors.

            public static bool PullTheFiles()
            {
                try
                {
                    NetworkCredential theNetworkCredential = new NetworkCredential("DOMAIN\\user", "password");
                    CredentialCache theNetcache = new CredentialCache
                    {
                        { new Uri("\\\\123.12.34.56\\AS400\\FILE\\SHARE\\"), "Negotiate", theNetworkCredential }
                    };
                    DirectoryInfo dirInfo = new DirectoryInfo("\\\\123.12.34.56\\AS400\\FILE\\SHARE\\");
                    foreach (var file in dirInfo.GetFiles())
                    {
                        if (ProcessPOList(file) == 0)
                        {
                            File.Move(file.FullName, settings.basePath + "Copies\\" + file.Name);
                        }
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    Utils.Update("Error:   " + ex.Message);
                    return false;
                }
            }

    Wednesday, September 19, 2018 12:24 PM