Is it possible to access a network folder with Directory.GetFiles() that I would normally have to enter my credentials for when opening through explorer?
Asked
Active
Viewed 1.4k times
0
-
1I think this answer can helps you http://stackoverflow.com/a/1197430/2392330 – Boris Parfenenkov Jul 16 '14 at 16:56
2 Answers
8
If the running user is the logon user (with profil loading) and have already access to the remote path (by entering credentials), your application, which may run with user's profile loaded, should access to the UNC path without any login.
Otherwise, you can use this piece of code to logon you can find in GitHub :
using (UNCAccessWithCredentials unc = new UNCAccessWithCredentials())
{
if (unc.NetUseWithCredentials("uncpath", user, domain, password))
{
// Directory.GetFiles() here
}
}

Perfect28
- 11,089
- 3
- 25
- 45
-
I tried that (logging in manually and then seeing if it would work) but no luck. I think the issue there might be that it's on a different domain that I access through VPN. – BVernon Jul 16 '14 at 17:10
-
+1 for the answer b/c I'm sure it works although I already followed the answer in idlerboris's comment. – BVernon Jul 16 '14 at 17:11
-
As I mentioned, I didn't use this answer but marking it since I imagine it works and I can't mark idlerboris's comment as the answer :) – BVernon Aug 04 '14 at 20:33
0
It is possible. I usually spawn a process to pass the credentials to the system. Please see the code posted below which does exactly this. Once the process has completed you will be able to use the network share.
public void MapPath() {
string strServer = “ServerName”;
string strShare = “ServerShare”;
string strUsername = “ServerUsername”;
string strPassword = “ServerPassword”;
Process pNetDelete = new Process();
pNetDelete.StartInfo.CreateNoWindow = true;
pNetDelete.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
pNetDelete.StartInfo.UseShellExecute = false;
pNetDelete.StartInfo.FileName = “net”;
pNetDelete.StartInfo.Arguments = string.Format(“use /DELETE {0}\
{1} /Y”, strServer, strShare);
pNetDelete.Start();
pNetDelete.WaitForExit();
Process pNetShare = new Process();
pNetShare.StartInfo.CreateNoWindow = true;
pNetShare.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
pNetShare.StartInfo.UseShellExecute = false;
pNetShare.StartInfo.RedirectStandardError = true;
pNetShare.StartInfo.RedirectStandardOutput = true;
pNetShare.StartInfo.FileName = “net”;
pNetShare.StartInfo.Arguments = string.Format(“use \\{0}\{1} /u:"{2}" "{3}"”,
strServer, strShare, strUsername, strPassword);
pNetShare.Start();
pNetShare.WaitForExit();
string strError = pNetShare.StandardError.ReadToEnd();
if (pNetShare.ExitCode != 0)
{
throw new Exception(strError);
}
}

ohlando
- 321
- 1
- 7