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.
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?
I found a way to get access :-) -
using System;
-
using System.Runtime.InteropServices;
-
using System.Security.Principal;
-
using System.IO;
-
-
namespace RemoteCredentials
-
{
-
class MainClass
-
{
-
[DllImport( "advapi32.dll", SetLastError = true )]
-
private static extern bool LogonUser( string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken );
-
-
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
-
private unsafe static extern int FormatMessage(int dwFlags, ref IntPtr lpSource, int dwMessageId, int dwLanguageId, ref String lpBuffer, int nSize, IntPtr *arguments);
-
-
[DllImport( "kernel32.dll", CharSet = CharSet.Auto, SetLastError = true )]
-
private static extern bool CloseHandle( IntPtr handle);
-
-
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
-
public extern static bool DuplicateToken( IntPtr existingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr duplicateTokenHandle );
-
-
-
// logon types
-
const int LOGON32_LOGON_INTERACTIVE = 2;
-
const int LOGON32_LOGON_NETWORK = 3;
-
const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
-
-
// logon providers
-
const int LOGON32_PROVIDER_DEFAULT = 0;
-
const int LOGON32_PROVIDER_WINNT50 = 3;
-
const int LOGON32_PROVIDER_WINNT40 = 2;
-
const int LOGON32_PROVIDER_WINNT35 = 1;
-
-
/// <summary>
-
/// The main entry point for the application.
-
/// </summary>
-
[STAThread]
-
static void Main(string[] args)
-
{
-
IntPtr token = IntPtr.Zero;
-
IntPtr dupToken = IntPtr.Zero;
-
-
bool isSuccess = LogonUser("userID", @"\\100.100.100.100\d$", "PassWd", LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref token);
-
if (!isSuccess)
-
{
-
RaiseLastError();
-
}
-
-
isSuccess = DuplicateToken( token, 2, ref dupToken );
-
if( !isSuccess )
-
{
-
RaiseLastError();
-
}
-
-
WindowsIdentity newIdentity;
-
WindowsImpersonationContext impersonatedUser = null;
-
DirectoryInfo dirInfo;
-
FileInfo[] files;
-
-
try
-
{
-
-
newIdentity = new WindowsIdentity(dupToken);
-
impersonatedUser = newIdentity.Impersonate();
-
-
dirInfo = new DirectoryInfo(@"\\100.100.100.100\d$\Test folder");
-
files = dirInfo.GetFiles();
-
}
-
finally
-
{
-
impersonatedUser.Undo();
-
}
-
-
foreach( FileInfo file in files )
-
{
-
Console.WriteLine( file.FullName );
-
}
-
-
isSuccess = CloseHandle( token );
-
if( !isSuccess )
-
{
-
RaiseLastError();
-
}
-
Console.ReadLine();
-
}
-
-
// GetErrorMessage formats and returns an error message
-
// corresponding to the input errorCode.
-
public unsafe static string GetErrorMessage( int errorCode )
-
{
-
int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100;
-
int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
-
int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
-
-
int messageSize = 255;
-
string lpMsgBuf = "";
-
int dwFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
-
-
IntPtr ptrlpSource = IntPtr.Zero;
-
IntPtr ptrArguments = IntPtr.Zero;
-
-
int retVal = FormatMessage(dwFlags, ref ptrlpSource, errorCode, 0, ref lpMsgBuf, messageSize, &ptrArguments);
-
if( retVal == 0 )
-
{
-
// throw new ApplicationException(string.Format( "Failed to format message for error code '{0}'.", errorCode ) );
-
Console.WriteLine(string.Format("Failed to format message for error code '{0}'.", errorCode));
-
}
-
-
return lpMsgBuf;
-
}
-
-
private static void RaiseLastError()
-
{
-
int errorCode = Marshal.GetLastWin32Error();
-
string errorMessage = GetErrorMessage(errorCode);
-
-
//throw new ApplicationException( errorMessage);
-
Console.WriteLine(string.Format("Error: {0}", errorMessage));
-
}
-
}
-
}
Sign in to post your reply or Sign up for a free account.
Similar topics |
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,...
|
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);...
|
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...
|
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...
|
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.
...
| |
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...
|
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...
|
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) --->...
|
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:
|
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...
|
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...
| |
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...
|
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...
|
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...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |