I am sharing function to upload your files on local hard drive to SharePoint document library. In my scenario I have a file on local hard drive and upload this to a SharePoint document library and delete the file presented on local drive. The source code is
// For Publish file to library
private void PublishWorkbook(string strTempLocalPath, string strLibraryURL, string strFileName)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite siteCollection = new SPSite(SiteURL))
{
using (SPWeb spWeb = siteCollection.OpenWeb())
{
SPList spList = spWeb.Lists[strLibraryURL];///Lists/Announcements
string fileName = strFileName;
FileStream fileStream = null;
Byte[] fileContent = null;
try
{
string docPath = strTempLocalPath; //physical location of the file
fileStream = File.OpenRead(docPath);
fileContent = new byte[Convert.ToInt32(fileStream.Length)];
fileStream.Read(fileContent, 0, Convert.ToInt32(fileStream.Length));
spWeb.AllowUnsafeUpdates = true;
spList.RootFolder.Files.Add(spList.RootFolder.Url + "/" + fileName, fileContent, true);
spList.Update();
spWeb.AllowUnsafeUpdates = false;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (fileStream != null)
{
fileStream.Close();
}
}
DeleteTempFile(strTempLocalPath);
}
}
});
}
// For delete file from local hard drive
static void DeleteTempFile(string strFilePath)
{
try
{
FileInfo TheFile = new FileInfo(strFilePath);
if (TheFile.Exists)
{
File.Delete(strFilePath);
}
else
{
throw new FileNotFoundException();
}
}
catch (FileNotFoundException ex)
{
//lblStatus.Text += ex.Message;
}
catch (Exception ex)
{
//lblStatus.Text += ex.Message;
}
}
// For Publish file to library
private void PublishWorkbook(string strTempLocalPath, string strLibraryURL, string strFileName)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite siteCollection = new SPSite(SiteURL))
{
using (SPWeb spWeb = siteCollection.OpenWeb())
{
SPList spList = spWeb.Lists[strLibraryURL];///Lists/Announcements
string fileName = strFileName;
FileStream fileStream = null;
Byte[] fileContent = null;
try
{
string docPath = strTempLocalPath; //physical location of the file
fileStream = File.OpenRead(docPath);
fileContent = new byte[Convert.ToInt32(fileStream.Length)];
fileStream.Read(fileContent, 0, Convert.ToInt32(fileStream.Length));
spWeb.AllowUnsafeUpdates = true;
spList.RootFolder.Files.Add(spList.RootFolder.Url + "/" + fileName, fileContent, true);
spList.Update();
spWeb.AllowUnsafeUpdates = false;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (fileStream != null)
{
fileStream.Close();
}
}
DeleteTempFile(strTempLocalPath);
}
}
});
}
// For delete file from local hard drive
static void DeleteTempFile(string strFilePath)
{
try
{
FileInfo TheFile = new FileInfo(strFilePath);
if (TheFile.Exists)
{
File.Delete(strFilePath);
}
else
{
throw new FileNotFoundException();
}
}
catch (FileNotFoundException ex)
{
//lblStatus.Text += ex.Message;
}
catch (Exception ex)
{
//lblStatus.Text += ex.Message;
}
}
Comments
Post a Comment