473,480 Members | 2,333 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

File.Copy to fileshare server

4 New Member
I need to copy some files to a server, that I can only access by logging in with different credentials from my own.
I want to be able to do the login stuff programatically.

How do I get File.Copy to use the credentials for the server?

I'm programming the client side, so it doesn't seem to have anything to do with Impersonate.
I need to copy files to multible servers, and multible users should run this client from their local machine.

I have been browsing around for days now, but so far I have not been lucky in my search.
Jul 21 '08 #1
2 1209
Plater
7,872 Recognized Expert Expert
Have you looked at the various GetAccessControl() and SetAccessControl() functions of the File object? There might be something there?
Jul 21 '08 #2
DarthIvan
4 New Member
I found a way to get access :-)
Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Runtime.InteropServices;
  3. using System.Security.Principal;
  4. using System.IO;
  5.  
  6. namespace RemoteCredentials
  7. {
  8.     class MainClass
  9.     {
  10.         [DllImport( "advapi32.dll", SetLastError = true )]
  11.         private static extern bool LogonUser( string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken );
  12.  
  13.         [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
  14.         private unsafe static extern int FormatMessage(int dwFlags, ref IntPtr lpSource, int dwMessageId, int dwLanguageId, ref String lpBuffer, int nSize, IntPtr *arguments);
  15.  
  16.         [DllImport( "kernel32.dll", CharSet = CharSet.Auto, SetLastError = true )]
  17.         private static extern bool CloseHandle( IntPtr handle);
  18.  
  19.         [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  20.         public extern static bool DuplicateToken( IntPtr existingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr duplicateTokenHandle );
  21.  
  22.  
  23.         // logon types
  24.         const int LOGON32_LOGON_INTERACTIVE = 2;
  25.         const int LOGON32_LOGON_NETWORK = 3;
  26.         const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
  27.  
  28.         // logon providers
  29.         const int LOGON32_PROVIDER_DEFAULT = 0;
  30.         const int LOGON32_PROVIDER_WINNT50 = 3;
  31.         const int LOGON32_PROVIDER_WINNT40 = 2;
  32.         const int LOGON32_PROVIDER_WINNT35 = 1;
  33.  
  34.         /// <summary>
  35.         /// The main entry point for the application.
  36.         /// </summary>
  37.         [STAThread]
  38.         static void Main(string[] args)
  39.         {
  40.             IntPtr token = IntPtr.Zero;
  41.             IntPtr dupToken = IntPtr.Zero;
  42.  
  43.             bool isSuccess = LogonUser("userID", @"\\100.100.100.100\d$", "PassWd", LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref token);
  44.             if (!isSuccess)
  45.             {
  46.                 RaiseLastError();
  47.             }
  48.  
  49.             isSuccess = DuplicateToken( token, 2, ref dupToken );
  50.             if( !isSuccess )
  51.             {
  52.                 RaiseLastError();
  53.             }
  54.  
  55.             WindowsIdentity newIdentity;
  56.             WindowsImpersonationContext impersonatedUser = null;
  57.             DirectoryInfo dirInfo;
  58.             FileInfo[] files;
  59.  
  60.             try
  61.             {
  62.  
  63.                 newIdentity = new WindowsIdentity(dupToken);
  64.                 impersonatedUser = newIdentity.Impersonate();
  65.  
  66.                 dirInfo = new DirectoryInfo(@"\\100.100.100.100\d$\Test folder");
  67.                 files = dirInfo.GetFiles();
  68.             }
  69.             finally
  70.             {
  71.                 impersonatedUser.Undo();
  72.             }
  73.  
  74.             foreach( FileInfo file in files )
  75.             {
  76.                 Console.WriteLine( file.FullName );
  77.             }
  78.  
  79.             isSuccess = CloseHandle( token );
  80.             if( !isSuccess )
  81.             {
  82.                 RaiseLastError();
  83.             }
  84.             Console.ReadLine();
  85.         }
  86.  
  87.         // GetErrorMessage formats and returns an error message
  88.         // corresponding to the input errorCode.
  89.         public unsafe static string GetErrorMessage( int errorCode )
  90.         {
  91.             int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100;
  92.             int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
  93.             int FORMAT_MESSAGE_FROM_SYSTEM  = 0x00001000;
  94.  
  95.             int messageSize = 255;
  96.             string lpMsgBuf = "";
  97.             int dwFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
  98.  
  99.             IntPtr ptrlpSource = IntPtr.Zero;
  100.             IntPtr ptrArguments = IntPtr.Zero;
  101.  
  102.             int retVal = FormatMessage(dwFlags, ref ptrlpSource, errorCode, 0, ref lpMsgBuf, messageSize, &ptrArguments);
  103.             if( retVal == 0 )
  104.             {
  105. //                throw new ApplicationException(string.Format( "Failed to format message for error code '{0}'.", errorCode ) );
  106.                 Console.WriteLine(string.Format("Failed to format message for error code '{0}'.", errorCode));
  107.             }
  108.  
  109.             return lpMsgBuf;
  110. }
  111.  
  112.         private static void RaiseLastError()
  113.         {
  114.             int errorCode = Marshal.GetLastWin32Error();
  115.             string errorMessage = GetErrorMessage(errorCode);
  116.  
  117.             //throw new ApplicationException( errorMessage);
  118.             Console.WriteLine(string.Format("Error: {0}", errorMessage));
  119.         }
  120.     }
  121. }
Jul 22 '08 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

0
2072
by: SeanR | last post by:
I have a function to copare two files. It will first copy the original file form a different server to a local temp path and then compare that version to a version that has been restored form tape....
1
6715
by: cnu | last post by:
My program generates a log file for every event that happens in the program. So, I open the file and keep it open till the end. This is how I open the file for writing: <CODE> public...
4
14468
by: R Reyes | last post by:
I am trying to code a file uploader (for forum/email attachments) from the client computer to a remote web server via the PUT method (since POST is not allowed ). However, the upload works ONLY...
5
1518
by: vul | last post by:
I'm developing Windows Service which is going to listen MS Fax service events and update the database when Fax Job changed its status. I need to read OutboxLOG.txt which is used by MS Fax service....
1
19843
by: ABCL | last post by:
Hi All, I am working on the situation where 2 different Process/Application(.net) tries to open file at the same time....Or one process is updating the file and another process tries to access...
13
11108
by: George | last post by:
Hi, I am re-writing part of my application using C#. This application starts another process which execute a "legacy" program. This legacy program writes to a log file and before it ends, it...
5
22962
by: =?Utf-8?B?U3BlZWR5?= | last post by:
Sorry for aksing such a basic question but I have searched the internet high and low and none of the solutions seem to help. Here is my (not working) code: FileStream fs = new...
3
12033
by: Mike | last post by:
Hi I have problem as folow: Caught Exception: System.Configuration.ConfigurationErrorsException: An error occurred loading a configuration file: Request for the permission of type...
0
3772
by: DeskUser | last post by:
Hello I have an asp.net application installed in several locations (framework 1.1). One of my clients is having a strange error when trying to access a certain aspx page:
0
7051
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
6915
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7097
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
6993
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
4794
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4493
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3003
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
1
567
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
193
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.