I have a piece of code in C# that would let me grab an Excel file in SharePoint and into a local folder.
Although I can access the file using my Windows login but when I try to run the package it gives me the following error:
The remote server returned an error: (403) Forbidden.
This is the piece of code that I am using :
// downloads the file from SharePoint or a file system location to a local folder
Dts.TaskResult = (int)ScriptResults.Success;
try
{
// obtain location of local folder from variable
DirectoryInfo dir = new DirectoryInfo(Dts.Variables["User::ImportFolder"].Value.ToString());
if (dir.Exists)
{
// Create the filename for local storage using
// the GUID from SharePoint as this will be unique.
FileInfo file = new FileInfo((dir.FullName + ("\\"
+ (Dts.Variables["User::WorkbookGUID"].Value.ToString() + Dts.Variables["User::Extension"].Value.ToString()))));
if (!file.Exists)
{
// get the path of the file we need to download
string fileUrl = Dts.Variables["User::EncodedAbsUrl"].Value.ToString();
if ((fileUrl.Length != 0))
{
// download the file from SharePoint or Archive file system to local folder
WebClient client = new WebClient();
if ((fileUrl.Substring(0, 4).ToLower() == "http"))
{
// download the file from SharePoint
client.Credentials = System.Net.CredentialCache.DefaultCredentials;
client.DownloadFile(fileUrl, file.FullName);
}
else
{
// copy file from remote file system
System.IO.File.Copy(fileUrl, file.FullName);
}
}
else
{
throw new ApplicationException("EncodedAbsUrl variable does not contain a value!");
}
}
}
else
{
throw new ApplicationException("ImportFolder does not exist!");
}
}
catch (Exception ex)
{
Dts.Events.FireError(0, String.Empty, ex.Message, String.Empty, 0);
Dts.TaskResult = (int)ScriptResults.Failure;
}
Dts.TaskResult = (int)ScriptResults.Success;