Search code examples
c#.netsharepointmosswindows-sharepoint-services

"A specified logon session does not exist. It may already have been terminated." when trying to copy a file using WindowsIdentity.Impersonate


I am trying to copy a file from sharepoint to a unc path. I am using the following code:

 var id = new WindowsIdentity("[email protected]");
 var p = new WindowsPrincipal(id);
 var wic = id.Impersonate();
 File.Move(oldName, newName);
 wic.Undo();

oldname is C:\test.txt newName is \\server\folder\test.txt

I am getting the error

A specified logon session does not exist. It may already have been terminated.

How do I go about removing this error OR copy a file from A to B(UNC path) using sharepoint.


Solution

  • You are not actually getting a logon token to impersonate. You need to call the LogonUser API to get a valid logon token, which you can use to impersonate that user.

    See this blog entry for example code in c# on impersonating a windows user. You can also see this KB article that also contains c# code (and a duplicatetoken call for issues with .net 1.0)