I have problems opening a network drive programmatically. I have used the way described here:Access a Remote Directory from C#. This is the proposed solution in many other Stackoverflow posts and on other sites. And I have not seen any other way to do it.
The proposed solution gives an exception: system error 67 "The network name cannot be found".
The problem is that the network name is correct and can be found. If I first make the connection in windows file explorer typing the same network name, username and password, the files can be accessed from the code.
Code as I want to make it following the proposed solution, which is not working:
var SambaSharePath = @"\\images.eksempel.dk\archive\public";
var SambaUsername = @"net\username";
var SambaPassword = ConfigurationManager.AppSettings["SambaPassword"];
networkCredential = new NetworkCredential(SambaUsername, SambaPassword);
string filename = Path.Combine(SambaSharePath, imagePath);
MemoryStream image = new MemoryStream();
using (var x = new NetworkConnection(SambaSharePath, networkCredential))
{
var stream = new FileStream(filename, FileMode.Open);
filename = Path.GetFileName(filename);
stream.CopyTo(image);
stream.Close();
}
return image;
To see how NetworkConnection works, use the link above.
Code which is working after the connection to the share is established in file explorer (but not before):
...
string filename = Path.Combine(SambaSharePath, imagePath);
var stream = new FileStream(filename, FileMode.Open);
...
I have tried any possible combinations of forward and backward slashes etc. for the sharename and username, to get the code working but nothing helps. So I have ruled out misspelling and formatting errors.
I have tried google the exception, but none of the explanations gave meaning in the context.
Does anybody have an idea of how to get the code working and what the is the cause of the error?
The workaround is to first establish the connection with file explorer, but that doesn't work automatically with server restart.
net use \\images.eksempel.dk\archive\public /u:youruser password
– SisyphusThe problem is that the network name is correct and can be found.
are you sure? You don't need any of this code to work with file shares. JustFile.Copy
is enough. Even the credentials aren't needed- there's no "samba account" or "samba password", the connection is made using the current account's credentials. Are you trying to use some Linux file storage acting as a SAMBA server? – WorrimentNetworkConnection
in the BCL. The class you tried to use does whatnet use
would do using interop, and is only necessary when you try to run code under a local (ie non-Domain) account. Ifnet use
works, this code should work as well. Post the actual full exception text. You may be trying to connect to a Linux box running a deprecated version of SMB for example. – Worriment