Wednesday, August 05, 2009

Upload a file to SharePoint - ASP.NET

Hi,

If you all have wished you can upload a file to SharePoint programatically using ASP.NET / C#, then this is the place you need to look into. The code for doing the same is as follows,

public static bool UploadFileToDocumentLibrary(string sourceFilePath, string targetDocumentLibraryPath,
string userName, string password, string domainName)
{
//Flag to indicate whether file was uploaded successfuly or not
bool isUploaded = true;
try
{
// Create a PUT Web request to upload the file.
WebRequest request = WebRequest.Create(targetDocumentLibraryPath);
// Set credential details as entered by the user
//**********************************************
CredentialCache myCredentialCache = new CredentialCache();
// Dummy names used as credentials.
myCredentialCache.Add(new Uri(targetDocumentLibraryPath), "Basic", new NetworkCredential(userName, password, domainName));
// Call 'GetCredential' to obtain the credentials specific to our Uri.
NetworkCredential myCredential = myCredentialCache.GetCredential(new Uri(targetDocumentLibraryPath), "Basic");
// Associating only our credentials.
request.Credentials = myCredential;
//**********************************************

//Set credentials of the current security context
//request.Credentials = CredentialCache.DefaultCredentials;
request.Method = "PUT";
// Create buffer to transfer file
byte[] fileBuffer = new byte[1024];
// Write the contents of the local file to the request stream.
using (Stream stream = request.GetRequestStream())
{
//Load the content from local file to stream
using (FileStream fsWorkbook = File.Open(sourceFilePath, FileMode.Open, FileAccess.Read))
{
//Get the start point
int startBuffer = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length);
for (int i = startBuffer; i > 0; i = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length))
{
stream.Write(fileBuffer, 0, i);
}
}
stream.Close();
}
// Perform the PUT request
WebResponse response = request.GetResponse();
//Close response
response.Close();
}
catch (Exception ex)
{
//Set the flag to indiacte failure in uploading
isUploaded = false;
throw new Exception(ex.Message);
}
//Return the final upload status
return isUploaded;
}

No comments: