I have a block of code that is executing without errors when i login as a system administrator on the SharePoint 2010 site. But i have problems in executing the same with a regular user account. Can someone please help me on how to execute a code block by logging in as a different SharePoint account (Admin account) using C# code.
Example:
Using(Domain,LoginID,Password)
{
//Execute Code
//logout as admin
}
Error Message on SharePoint 2010:
Error Occured: System.UnauthorizedAccessException: Access to the path 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\template\layouts\Test\Dev\ABC.xlsx' is denied. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode) at System.Web.HttpPostedFile.SaveAs(String filename) at App.Test.btnFileUpload_Click(Object sender, EventArgs e)
Code Sample:
if (fileUpload.HasFile)
{
strTarget = Server.MapPath(fileUpload.FileName);
string[] arrCheckExtension = strTarget.Split('.');
if (arrCheckExtension.Length >= 2)
{
if (arrCheckExtension[1].ToString().Equals("xls") || arrCheckExtension[1].ToString().Equals("xlsx"))
{
fileUpload.SaveAs(strTarget);
strConnForExcel = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0;HDR=YES;IMEX=1;""", strTarget);
strQueryForExcel = String.Format("select id from [{0}$]", "Test");
OleDbDataAdapter adap = new OleDbDataAdapter(strQueryForExcel, strConnForExcel);
ds = new DataSet();
adap.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if (strids == "")
{
strids += ds.Tables[0].Rows[i]["id"].ToString();
}
else
{
strids += "," + ds.Tables[0].Rows[i]["id"].ToString();
}
}
txtUpload.Text = strids;
}
}
else
{
Response.Write("<script language='javascript'>alert('Please Select File with .xls or xlsx Extension');</script>");
}
}
}