I am using this Impersonator class to copy files to a Directory with access rights.
public void CopyFile(string sourceFullFileName,string targetFullFileName)
{
var fileInfo = new FileInfo(sourceFullFileName);
try
{
using (new Impersonator("username", "domain", "pwd"))
{
// The following code is executed under the impersonated user.
fileInfo.CopyTo(targetFullFileName, true);
}
}
catch (IOException)
{
throw;
}
}
This code work almost perfectly. The problem I am facing is when the sourceFullFileName is a file located in folder like C:\Users\username\Documents where the original user has access but the impersonator not.
The exception I am getting while trying to copy a file from such location is:
An unhandled exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll Additional information: Access to the path 'C:\Users\username\Documents\file.txt' is denied.
Before impersonation, the current user has access to the source file path but not to the destination file path.
After impersonation, it is quite the opposite: the impersonated user has access to the destination file path but not to the source file path.
If the files are not too large, my idea would be the following:
public void CopyFile(string sourceFilePath, string destinationFilePath)
{
var content = File.ReadAllBytes(sourceFilePath);
using (new Impersonator("username", "domain", "pwd"))
{
File.WriteAllBytes(destinationFilePath, content);
}
}
I.e.:
Methods and classes used here:
File.ReadAllBytes
to read everything into memory.File.WriteAllBytes
to write everything from memory into the file.Impersonator
to temporarily change the identity of the current thread.