I need to access a file from a network drive with a user who may not be in the domain.
My current code is:
private async Task GetUxVersionsFromServer()
{
string path = @$"\\{IpAddress}\...\...\...";
if(!await GetFiles(path))
{
using (UNCAccessWithCredentials unc = new UNCAccessWithCredentials())
{
bool retry = true;
do
{
(var ok, var username, var password) = _dialogService.ShowPasswordInput();
if (ok)
{
if (unc.NetUseWithCredentials(path, username, "domain", password))
{
await GetFiles(path);
retry = false;
}
}
else
{
retry = false;
}
} while (retry);
}
}
}
private async Task<bool> GetFiles(string path)
{
try
{
var zipFiles = await Task.FromResult(System.IO.Directory.GetFiles(path, "VERSION*.zip"));
Versions = new ObservableCollection<string>(zipFiles);
return true;
}
catch (IOException)
{
return false;
}
}
I use the class UNCAccessWithCredential
from here
It works fine.
If the user has access to the directory, the password entry should not appear. The only problem is that I can't test if the Windows user has access to the directory without catching an exception.
Is there a way to query if the logged in Windows user has access to a network directory or not?
Is there a way to query if the logged on Windows user is in the domain?
Finally I solved it this way:
private async Task GetUxVersionsFromServer()
{
string path = @$"\\{server}\...";
if (Environment.UserDomainName.ToLower() != "myDomain")
{
bool success = false;
bool ok;
do
{
(bool result, var username, var password) = _dialogService.ShowPasswordInput();
ok = result;
if (ok)
{
try
{
using (new NetworkConnection(path, new NetworkCredential($@"myDomain\{username}", password)))
{
success = await GetFiles(path);
}
}
catch (System.ComponentModel.Win32Exception ex)
{
success = false;
}
}
} while (!success && ok);
if(!ok)
{
int test = 0;
}
}
else
{
await GetFiles(path);
}
}
I took the class NetworkConnection
from here