I am working on a ASP.NET application using C# that is trying to read some files from a website by logging in and then writing the files on local drive.
I have already passed network credentials to logon to the website by reading the default credentials using –
request.Proxy.Credentials = CredentialCache.DefaultCredentials;
Now i want to store the files on a server directory that requires some credentials to access the location.
Code of logging on to the website –
string webUrl = "https://web.site.com/";
string formParams = string.Format("user={0}&password={1}", username, password);
WebRequest req = WebRequest.Create(webUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
req.Proxy.Credentials = CredentialCache.DefaultCredentials;
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];
And the location is \\11.11.11.11\Folder\
How can I pass credentials for accessing that location?
I have learned about impersonation but not getting anything helpful so far. I have credentials that gives access to the location. But how can I do so by using C# code?
Thanks in advance 🙂
You can use the
LogonUserAPI for this. You use theLogonUserfunction to create a token that represents theWindowsIdentityyou want to impersonate. You then create aWindowsIdentityusing the token and callImpersonateon the identity. All code that follows runs under the impersonated identity.Make sure that you always
UndotheWindowsImpersonationContext.