Click here to Skip to main content
15,569,774 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,

I am using Stream Writer/Reader and don't have a problem
reading and writing from my local machine, but I need to
read/write now to a shared network folder on another PC.

I tried just changing the file path, but with no luck.
The network PC also requires a username and password
that I do have.

How would I do this?

Please any help would be appreciated!
Posted

One option would be to use Windows Explorer to Map the network path to a drive letter on your local machine, specifying credentials and "reconnect on login". That way you can just access the path like a local drive
 
Share this answer
 
Comments
Maciej Los 30-May-12 11:21am    
Good answer, my 5!
there are options to set the usercredentials during a copy of a file. So first geenrate it on the generatormachine and after generating copy it to the shared pc.
See Here[^] for a lot of google hits opn how to do that.

One advantage of this approach is that the file is not accesible to other users during generation.

C#
#region consts
      const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
      const int LOGON32_PROVIDER_DEFAULT = 0;
      #endregion

      #region Windowns API
      [DllImport("advapi32.DLL", SetLastError = true)]
      public static extern int LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
      #endregion

IntPtr admin_token = default(IntPtr);
                        WindowsIdentity wid_current = WindowsIdentity.GetCurrent();
                        WindowsIdentity wid_admin = null;
                        WindowsImpersonationContext wic = null;
                        string[] split = new string[1];
                        split[0] = "\\";
                        string[] temp = ServerName.Split(split, StringSplitOptions.RemoveEmptyEntries);
                        string domain = String.Empty;
                        string userName = ServerUserName;
                        string password = Password;
                        if (LogonUser(userName, domain, password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref admin_token) != 0)
                        {
                            try
                            {
                            wid_admin = new WindowsIdentity(admin_token);
                            wic = wid_admin.Impersonate();
                            // do your thing
                            }
                            catch { } // if case of you do something with excepions
                            finally
                            {
                                if (wic != null)
                                {
                                    wic.Undo();
                                }
                            }
                        }
 
Share this answer
 
v2
Comments
Oleksandr Kulchytskyi 30-May-12 9:55am    
Nice solution, but you are not pointed to a few crucial moments.
First of all , admin_token needs to be released by calling WinApi method CloseHandle.
Second one, WindowsImpersonationContext implements IDisposable, so you should call Dispose() method.
Herman<T>.Instance 30-May-12 9:59am    
or set in using() is possible too. Good you told me. I was not aware of the IDisposable. Will change it in my own code.

The code works great for me but is my Undo() not the same as your CloseHandle? perhaps you can add a solution based on my code
Oleksandr Kulchytskyi 30-May-12 10:54am    
Yep, i can.
Undo() is not the same as CloseHandle. CloseHandle, release unmanaged resources which you created with LogonUser().

#region consts
const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
const int LOGON32_PROVIDER_DEFAULT = 0;
#endregion

#region Windowns API
[DllImport("advapi32.DLL", SetLastError = true)]
public static extern int LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
internal static extern bool CloseHandle(IntPtr handle);

[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool DuplicateToken(IntPtr hToken,int impersonationLevel,out IntPtr hNewToken);
#endregion

IntPtr admin_token = default(IntPtr);
IntPtr dupToken = default(IntPtr);
WindowsIdentity wid_current = WindowsIdentity.GetCurrent();
WindowsIdentity wid_admin = null;
WindowsImpersonationContext wic = null;
string[] split = new string[1];
split[0] = "\\";
string[] temp = ServerName.Split(split, StringSplitOptions.RemoveEmptyEntries);
string domain = String.Empty;
string userName = ServerUserName;
string password = Password;
if (LogonUser(userName, domain, password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref admin_token) != 0)
{
if(DuplicateToken(admin_token, 2, out dupToken) != 0)
{
try
{
wid_admin = new WindowsIdentity(dupToken);
wic = wid_admin.Impersonate();
// do your thing
}
catch { } // if case of you do something with excepions
finally
{
if (wic != null)
{
wic.Undo();
}
if(admin_token!=default(IntPtr))
CloseHandle(admin_token);

if(dupToken!=default(IntPtr))
CloseHandle(dupToken);
}
}
}
Herman<T>.Instance 31-May-12 3:49am    
thanks. I'll test is this evening.
Herman<T>.Instance 31-May-12 9:48am    
this part does not work: if(DuplicateToken(admin_token, 2, out dupToken) != 0)

DuplicateToken is a boolean
First of all, you are performs such action in context of current running user on your local PC!! For user impersonation you should be looked at WinApi methods, and with help of P\Invoke use it.WinApi methods list see below: 
- LogonUser;
 - DuplicateToken;
 - RevertToSelf;
 - CloseHandle;
 
Share this answer
 
I want to share with you some useful code snippet, which i use in my own project for user impersonation.
take a look on it:
C#
[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode = true)]
	[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
	internal class MySafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
	{
		private MySafeTokenHandle()
			: base(true)
		{
		}
		[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
		override protected bool ReleaseHandle()
		{
			return NativeMethods.CloseHandle(handle);
		}
	}

	[SuppressUnmanagedCodeSecurity()]
	internal static class NativeMethods
	{
		#region P/Invoke
		internal const int LOGON32_LOGON_INTERACTIVE = unchecked((int)2);
		internal const int LOGON32_PROVIDER_DEFAULT = unchecked((int)0);

		[DllImport("advapi32.dll")]
		internal static extern int LogonUserA(String lpszUserName,
			String lpszDomain,
			String lpszPassword,
			int dwLogonType,
			int dwLogonProvider,
			out MySafeTokenHandle phToken);
		[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
		internal static extern int DuplicateToken(MySafeTokenHandle hToken,
			int impersonationLevel,
			out MySafeTokenHandle hNewToken);

		[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
		[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
		internal static extern bool CloseHandle(IntPtr handle);
		#endregion
	}

	[SecurityPermissionAttribute(SecurityAction.InheritanceDemand, UnmanagedCode = true)]
	public class Impersonation : IDisposable
	{
		WindowsImpersonationContext impersonationContext;

		public void ImpersonateUser(String userName, String domain, String password)
		{
			WindowsIdentity tempWindowsIdentity;
			MySafeTokenHandle token;
			MySafeTokenHandle tokenDuplicate;
			if (NativeMethods.LogonUserA(userName, domain, password, NativeMethods.LOGON32_LOGON_INTERACTIVE, NativeMethods.LOGON32_PROVIDER_DEFAULT, out token) != 0)
			{
				using (token)
				{
					if (NativeMethods.DuplicateToken(token, 2, out tokenDuplicate) != 0)
					{
						using (tokenDuplicate)
						{
							if (!tokenDuplicate.IsInvalid)
							{
								tempWindowsIdentity = new WindowsIdentity(tokenDuplicate.DangerousGetHandle());
								impersonationContext = tempWindowsIdentity.Impersonate();
								return;
							}
						}
					}
				}
			}
			else
				throw new Exception("LogonUser failed: " + Marshal.GetLastWin32Error().ToString());
		}

		public void Dispose()
		{
			impersonationContext.Undo();
			GC.SuppressFinalize(this);
		}
	}

	public class ImpersonationExecutor
	{
		public string USR { get; set; }
		public string DOMAIN { get; set; }
		public string PWD { get; set; }

		public ImpersonationExecutor(string userName, string domainName, string password)
		{
			USR = userName;
			DOMAIN = domainName;
			PWD = password;
		}

		public void ExecuteCode<t>(Action<t> action, T arg)
		{
			using (Impersonation user = new Impersonation())
			{
				user.ImpersonateUser(USR, DOMAIN, PWD);
				action(arg);
			}
		}
	}

	public class ImpersonationFactory
	{
		public static ImpersonationExecutor Create(string UserName, string Domain, string Password)
		{
			return new ImpersonationExecutor(UserName, Domain, Password);
		}
	}

	USage:
	string from = "from";
	string to = "to";
	byte[] buffer = null;
	ImpersonationFactory.Create("userA", "domainA", "passwordA").ExecuteCode<string>(delegate(string path) { buffer = File.ReadAllBytes(path); }, from);
	ImpersonationFactory.Create("userB", "domainB", "passwordB").ExecuteCode<string>(delegate(string path) { File.WriteAllBytes(path, buffer); }, to);
</string></string></t></t>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900