Overview:
Imagine you have one moss site and one shared folder over network, and you are getting reports or xml files periodically from different departments to that shared folder. I had similar condition and client wants that reports & xml files imported periodically to SharePoint site. The idea is create web service that has timer event, which uploads file to SharePoint.
Here I’m showing steps to make that happen.
Steps:
1. Create new Web Service project
2. Declare timer variable to class level.
System.Timers.Timer tm = new System.Timers.Timer();
3. In web service constructor initialize timer properties and add timer event.
public Service1()
{
tm.Elapsed += new ElapsedEventHandler(OnElapsedTime);
int minute = 1; //***after this time , reports will be imported to sharepoint
tm.Interval = minute * 60000;
tm.Start();
tm.Enabled = true;
}
4. Timer event OnElapsedTime will call UploadFileToDocumentLibrary method.
protected void OnElapsedTime(object source, ElapsedEventArgs e)
{
tm.Stop();
//sending reports to sp reports library
foreach (string strFile in Directory.GetFiles(@"C:\reports\all")) //my shared report directory
{
try
{
LogToFile(strFile + " copied");
UploadFileToDocumentLibrary(strFile, @"http://mossserver:1234/Reports/" + Path.GetFileName(strFile));
}
catch (Exception ex)
{
LogToFile(ex.Message.ToString());
}
}
}
5. Log error or other activities to log file, if you want to.
private void LogToFile(string contents)
{
FileStream fs = new FileStream(@"C:\UploadErrorLog.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.WriteLine(contents);
sw.Flush();
sw.Close();
}
6. Here is the method to upload file to sharepoint document library.(method by Rizvi)
/// <summary>
/// Uploads file to document library in sharepoint.
/// </summary>
/// <param name="FilePath">Source File Path.</param>
/// <param name="DocumentLibraryPath">Target Document Library Path</param>
/// <returns>true if uploaded successfully, false otherwise</returns>
public static bool UploadFileToDocumentLibrary(string FilePath, string DocumentLibraryPath)
{
bool isUploaded = true;
try
{
WebRequest request = WebRequest.Create(DocumentLibraryPath);
//provide network credentials used for authentication
request.Credentials = CredentialCache.DefaultCredentials;
request.Method = "PUT";
byte[] fileBuffer = new byte[1024];
using (Stream stream = request.GetRequestStream())
{
using (FileStream fs = File.Open(FilePath, FileMode.Open, FileAccess.Read))
{
int startBuffer = fs.Read(fileBuffer, 0, fileBuffer.Length);
for (int i = startBuffer; i > 0; i = fs.Read(fileBuffer, 0, fileBuffer.Length))
{
stream.Write(fileBuffer, 0, i);
}
}
}
WebResponse response = request.GetResponse();
response.Close();
}
catch
{
isUploaded = false;
}
return isUploaded;
}
7. Deploy and start web service.
Alternative efficient method:
Well, above method gets the job done.
But if you really want really clean version of upload file method, here is the method that I use to upload infopaht form to form library.
In later articles you will find how to programatically create infopath form from the existing template and upload it to form library, with batch operation..
You need to pass data in memorystream format. It seems this method is bit faster compared to above.
I perform xmldoc.Save(ms); to convert my programatically generated xml form to memorystream, then call method below.
/// <summary>
/// Uploads file to document/form library in sharepoint
/// </summary>
/// <param name="targetFileName">target filename ***with Extension***</param>
/// <param name="targetFormLibraryPath">target documnet/form library path on sharepoint server.</param>
/// <param name="msFileData">File data in form of Memorystream</param>
/// <returns>true if uploaded successfully, false otherwise</returns>
static public bool UploadToLibrary(string targetFileNameWithExtension, string targetFormLibraryPath ,MemoryStream msFileData)
{
bool isUploaded = true;
try
{
using (WebClient client = new WebClient())
{
//provide network credentials used for authentication
client.Credentials = CredentialCache.DefaultCredentials;
// Upload the newly created form to a SharePoint form library
client.UploadData(Path.Combine(targetFormLibraryPath,targetFileNameWithExtension), "PUT", msFileData.GetBuffer());
}
}
catch
{
isUploaded = false;
}
return isUploaded;
}
Thanks