pass authentication information with file read request to a network computer
I am writing a windows application in which I am trying to access a file on a network computer and it is obviously throwing authentication exception
"Logon failure: unknown user name or bad password"
I am not sure how to pass authentication information in code below ?
try
{
string fname = @"\\ServerNAme\SHaredFolder\somefile.log";
StreamReader sr = new StreamReader(fname);
textbox1.Text = sr.ReadLine();
}
catch (System.IO.IOException ex) //cathes System.IO.IOException
{
//ex.message is "Logon failure: unknown user name or bad password"
}
[744 byte] By [
bilalso] at [2008-2-11]
The above code is going to access the network share using the credentials of the user running the application. You should grant appropriate permissions to an Active Directory or NT Group and add application users to that group. You'll want to ensure that the group has appropriate permissions to both the share and the underlying file on NTFS. If you get either wrong, you won't have access. The easiest way to determine this is to open the file from Explorer. If you can open it from Explorer, you should be able to open it from your WinForms app.
Another option would be to impersonate a user that has the appropriate access to the file on the network share. This is more complex and you run into the problem that you'll need to store the username/password for the user somewhere that the application can get to. If the application can get to the username/password, so can a malicious user. So easiest just to grant permission to a group and include the user in that group directly.
If the application is running under partial trust, you might not have network share permission depending on the zone that you're running from. In that case, I would recommend signing your assembly and granting it sufficient privileges to access a network share.
So how would I go about doing the impersonation as you mentioned?
I have an app that needs to access shares on several servers and scan the folder for file attributes, but some of the servers are not in a domain so I will need to be able to impersonate a local user account for the access to the share.
I just cannot find anything in .NET that provides for this even though there are obvious classes for the same thing for web, FTP and all kinds of other access. I just do not know what I am looking for it seems.