简体   繁体   中英

Remote File Accessing from Sharepoint Application Page

In my Sharepoint Application Page, I'm trying to copy a file from a Network Shared Folder.. And my code's like below..

    try
    {
        File.Copy("\\MShare\Public\Test.txt", "C:\Temp\Test.txt", true);
        LblMessage.Text = "File copied.";
    }
    catch (Exception ex)
    {
        LblMessage.Text = ex.ToString() + " - " + ex.Message;
    }

It's working well if I test the same code in ASP.NET Website.. But I'm getting error as follow with SP Application Page..

System.UnauthorizedAccessException: Access to the path '\\MShare\Public\Test.txt' is denied. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.File.InternalCopy(String sourceFileName, String destFileName, Boolean overwrite) at System.IO.File.Copy(String sourceFileName, String destFileName, Boolean overwrite) at TestApp.PullingFile.ButGet_Click(Object sender, EventArgs e) - Access to the path '\\MShare\Public\Test.txt' is denied.

I've tried implementing impersonation by following this post.. Not working.. And I tried by changing at web.config with <trust level="WSS_Medium" originUrl="" /> also..

By default SharePoint uses impersonating . Meaning your code runs under the credentials of the current user. This user has not (and should not have) access to the server's file system.

What you can do is revert to the system accounts credentials in order to access the file system:

SPSecurity.RunWithElevatedPrivileges(() =>
{
    File.Copy("\\MShare\Public\Test.txt", "C:\Temp\Test.txt", true);
});

What you have to keep in mind:

  1. The system account (application pool account) has not necessarily access to the file system (least privileges scenario). ( SO question )
  2. The system account (application pool account) has not necessarily access to the network share.
  3. Any user accessing your application page can execute your file copy code. You have to care about authorization yourself.

Last but not least :
Why do you have to copy the file to the server's file system after all? Do you need it physically on the server or is this just temporary (as one could guess by the path).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM