473,546 Members | 2,243 Online
Bytes | Software Development & Data Engineering Community
+ 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 1214
Plater
7,872 Recognized Expert Expert
Have you looked at the various GetAccessContro l() and SetAccessContro l() 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
2081
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. Once the compare is complete the file that was copied to a temp location needs to be deleted. I am using the method file.copy(sourcePath,...
1
6728
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 CLogHandler() { this.m_fsLog = new FileStream(strTodaysLogFile, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.Read);...
4
14484
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 when the file is inside a shared folder on my computer. If I try to upload from any other folder it does not work. Why is this? Reason being that...
5
1525
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. I either would like to copy it and to work with its copy to use its data for a database update or to copy the data from OutboxLOG.txt into another...
1
19870
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 it, it throws an exception. How to solave this problem? So second process can wait until first process completes its processing on the file. ...
13
11117
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 writes a specific string to the log file. My original program (MKS Toolkit shell program) which keeps running "grep" checking the "exit string" on...
5
22992
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 FileStream(FileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None); fs.lock(0, fs.Length); So as you can see I am trying three different techniques at...
3
12036
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 'System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed. (machine.config) --->...
0
3780
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
7507
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7435
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7947
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7461
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
5080
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3492
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3472
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1046
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
747
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.