1

I am developing a winform application on C# where I need to access a network folder but i get logon user password exception. How can i provide user credentials through application?

double length = ((Directory.GetFiles("\\192.168.50.107\Destination", "*", SearchOption.AllDirectories).Sum(t => (new FileInfo(t).Length)) / 1024) / 1024) / 1024;
Mohammad Rashid
  • 138
  • 3
  • 16
  • Go and research impersonation. – Equalsk Mar 31 '17 at 12:16
  • Possibly related http://stackoverflow.com/questions/659013/accessing-a-shared-file-unc-from-a-remote-non-trusted-domain-with-credentials – Codor Mar 31 '17 at 12:17
  • 1
    Possible duplicate of [How to provide user name and password when connecting to a network share](http://stackoverflow.com/questions/295538/how-to-provide-user-name-and-password-when-connecting-to-a-network-share) – Jurjen Mar 31 '17 at 12:17

2 Answers2

0

Try this

using (new NetworkConnection(@"\\192.168.50.107\Destination", readCredentials))
using (new NetworkConnection(@"\\192.168.50.107\Destination", writeCredentials)) {
   double length = ((Directory.GetFiles("\\192.168.50.107\Destination", "*",    SearchOption.AllDirectories).Sum(t => (new FileInfo(t).Length)) / 1024) / 1024) /   1024;
}

Font: How to provide user name and password when connecting to a network share

Community
  • 1
  • 1
Gabriel Bernardone
  • 322
  • 2
  • 5
  • 15
  • there is probably no need for writecredentials in this case – Cee McSharpface Mar 31 '17 at 12:22
  • @Gabriel Bernardone I tried your code with helpm of [link](http://stackoverflow.com/questions/5433570/access-a-remote-directory-from-c-sharp) but it gives error .. "the network name can not be found" – Mohammad Rashid Apr 01 '17 at 04:56
0
 private void ConnectToNetwork()
    {
        NetworkCredential theNetworkCredential = new NetworkCredential(@"UserName", "Password");
        CredentialCache theNetCache = new CredentialCache();
        theNetCache.Add(new Uri(@"\\NAS"), "Basic", theNetworkCredential);
    }
Jameson1.0
  • 46
  • 5
  • Call this method before trying to access the file on the network. – Jameson1.0 Mar 31 '17 at 12:54
  • And I noticed while doing this for my Project that the networkcredential didnt like when i used the IP address. So I used the name of IP instead and it works for me. – Jameson1.0 Mar 31 '17 at 12:57
  • I tried in both ways.. with IP and with server name but it still gives error path not found.. `theNetCache.Add(new Uri(@"\\192.168.50.107"), "Basic", theNetworkCredential);` – Mohammad Rashid Apr 01 '17 at 04:53
  • Maybe you need to check your network credentials for the user you are trying to log in with. You should have read and write privileges – Jameson1.0 Apr 04 '17 at 11:40