in

SharePoint Blogs

The Best Place for SharePoint-related Blogs

This Blog

Syndication

Tags

No tags have been created or used yet.

Archives

apichot's blog

SharePoint 2007: Upload a Document with Its Meta-Data

Recently, I had to build the following application: pdf documents were generated automatically from an external application and associated with a set of text files containing their meta-data. The main goal was to upload those documents into a SharePoint document list, with there meta-data extracted from the text file. Then a workflow is invoked for approbation with several parameters depending on meta-data.
In this article I'll focus on importing files into the list with their meta-data.

The first thought that came to my mind was about uploading one document into the list, then adding meta-data one by one to their corresponding columns. But because I have to manage versions for this list, this solution seems not adequate: one update for the document and one update for the meta-data means two versions instead of one.
But I've found one overloading really interesting.

First, let's consider the list like a folder. And inside this folder we have a collection of files. If I add a file to this collection, this is the same as uploading a file, no ?
The folder name is the internal name of the list. The internal name is the name you first set for the list. For instance, if you have created a Purchase Order list with the name PurchaseOrder, then you have modified the name to Purchase Order, the folder name will be PurchaseOrder. You can check it with the url, i.e. http://dcmoss:50010/testgy/PurchaseOrder/ where PurchaseOrder is the name of the folder.

SPFolder folder = _web.GetFolder("internal list name");
SPFileCollection files = folder.Files;

Then I get the file itself, storing it in a memory stream

FileStream fStream = File.OpenRead("fileName");

And, at last, I create the URL of the file, with the file name

string url = "url web site" + "internal list name" + "/" + Path.GetFileName("fileName");

Meta-data have to be stored into a Hashtable

HashTable MetaDataTable = new HashTable();
MetaDataTable.Add("column name", "value");

In fact, I have a class which parse the text file and send me back a Hashtable. Then I add everything to the file collection

SPFile currentFile = files.Add(url, fStream, MetaDataTable, true);

The boolean value allow you to replace a file if it is already existing
In one line, we add the file with its meta-data ! Not bad.

Here is an example of code for adding a document with its meta-data

//Using required, especially System.IO;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using Microsoft.SharePoint;
using System.IO;

namespace DocImport
{
public class DocManagement {
//Some variables
private string _DestUrlPath = string.Empty;
private string _DestFolder = string.Empty;

private SPSite _site = null;
private SPWeb _web = null;

public DocManagment(string DestUrl, string DestFolder) {
_DestUrlPath = DestUrl;
_DestFolder = DestFolder;
_site = new SPSite(_DestUrlPath);
_web = _site.OpenWeb();
}


private bool _uploadDocument(string pdfFile, string txtFile) {
try {
//This is mandatory for avoiding an error
_web.AllowUnsafeUpdates = true;
//Use the list as a folder
SPFolder folder = _web.GetFolder(_DestFolder);
SPFileCollection files = folder.Files;
//Get the file
FileStream fStream = File.OpenRead(pdfFile);
HashTable MetaDataTable = new HashTable();
MetaDataTable.Add("nom de colonne", "valeur");

//Set the destination url for SharePoint
string url = _DestUrlPath + _DestFolder + "/" + Path.GetFileName(pdfFile);
//Add document to the list with metadata, and overwrite an existing document
with the same name
SPFile currentFile = files.Add(url, fStream, MetaDataTable, true);
fStream.Close();
return true;
} catch (Exception x) {
throw new Exception(x.Message);
}
}
}

Comments

 

steven-fowler.com said:

Another helpful post on uploads to MOSS

June 19, 2007 8:00 PM
 

steven-fowler.com said:

Another helpful post on uploads to MOSS

June 19, 2007 8:00 PM
 

nav said:

i tried this but its not updating the columns only adding the file to doclib...

and cant find a HashTable Type in C#..

is it working for you??????

June 21, 2007 9:08 AM
 

Sharepoint desde cero said:

En esta nueva sección iré publicando pequeños fragmentos de código de ejemplo para realizar tareas en

July 10, 2007 6:51 PM
 

zto said:

It should be Hashtable, not HashTable. I don't know why the code is not capitalized properly.

July 18, 2007 9:03 AM
 

Dominic said:

I'm also using this approach but having problems managing a few fields any hints?

Title,

Created by,

Modified by

Creation date

Modification date.

Cheers

Dom.

July 31, 2007 12:06 PM
 

Jora said:

When the files are added/uploaded to my document list, they become Read Only and cannot be modified. Please help :-)

August 15, 2007 6:41 PM
 

Craig said:

Fantastic, works really well, except if I add "Title" to the hashtable, this value is not updated - it remains blank.  Any suggestions?

August 17, 2007 12:15 AM
 

Robert said:

Yeah same here I can update "lookup" columns using the syntax "ID#;VALUE", and plain text fields, but i am having trouble updating "choice" columns and the "content type". This is really annoying as i have created some custom code to change the values after the item is added to the list but that increments the version number :s

August 22, 2007 1:01 PM
 

SJ said:

How to update lookup columns... can any one help me with the syntax and also choice columns

September 24, 2007 12:46 PM
 

Srini said:

While upload the doc to sharepoint it asking for user name and password. But sharepoint site is anonymous access. Even i am using impersonate class also.,

October 22, 2007 12:15 PM
 

Rat Rod said:

Craig to upload Metadata for "Title" use the field vti_title, such as :

MetaDataTable.Add("vti_title", "My Title");

October 24, 2007 9:15 AM
 

Anil Madan said:

Hi!

I am new to the sharepoint. I a trying to migrate data from 2001 to 2007. I am able to put the other data except

Created by,

Modified by

Creation date

Modification date.

I will appreciate if please help me in updating these fields. Thanks a lot

October 25, 2007 11:04 AM
 

jason said:

files.Add() - there are 3 overideable method and none take 4 parameter. help

November 6, 2007 3:00 PM
 

Fragmentos de código: Subir un documento con metadatos | Mundo Sharepoint said:

Pingback from  Fragmentos de código: Subir un documento con metadatos | Mundo Sharepoint

December 4, 2007 1:25 PM
 

xanderphillips said:

I'd like to import about 150k pdf files into SP2k7, but somehow retain the original file creation date or the last modified date of the original source document so that I can setup views sorted by that field.  (Using one of the standard document fields is important as it new documents will be created natively in SP2k7 and sorts need to treat them the same as imported ones.)

Suggestions?

January 24, 2008 12:24 PM
 

Cong said:

Have you experienced with Sharepoint escape characters of Metadata Name?

For example: when I submit an document with properties "my e-mail"

Sharepoint rename it to "my e_x002d_mail". And I cannot set the value of it ??

January 24, 2008 10:39 PM
 

Michael Baltaks said:

Here is the example code I put together to both upload a file, and set the metadata that won't work using the hashtable method during the actual upload.

Just create a dummy text file at C:\dummy.txt (unless you can get Microsoft.SharePoint working on a different OS) and create a doc lib on your MOSS2007 site at the top level called Docs.

using System;

using System.Collections.Generic;

using System.Text;

using System.IO;

using System.Collections;

using Microsoft.SharePoint;

namespace SharePointUpload

{

class Program

{

static void Main(string[] args)

{

Microsoft.SharePoint.SPSite sc = new Microsoft.SharePoint.SPSite("http://server.domain.name");

Microsoft.SharePoint.SPWeb web = sc.OpenWeb();

SPListCollection lc = web.GetListsOfType(SPBaseType.DocumentLibrary);

SPList listSource = lc["Docs"];

SPFolder folder = web.GetFolder("/Docs");

SPFileCollection files = folder.Files;

FileStream localFile = File.OpenRead("C:\\dummy.txt");

Hashtable metadataTable = new Hashtable();

metadataTable.Add("vti_title", "Dummy Test Text");

// next line does not work

metadataTable.Add("vti_timelastmodified", "2005-12-25 09:00:00");

SPFile spFile = files.Add("/Docs/dummy.txt", localFile, metadataTable, true);

localFile.Close();

foreach (SPListItem li in listSource.Items)

{

System.Console.Out.WriteLine(li.Url);

if (li.Url == "Docs/dummy.txt")

{

li["Created"] = "2004-03-01 07:00:00";

// Users have to exist in SharePoint already, referenced by ID

li["Author"] = "5";

li["Modified"] = "2005-02-20 09:00:00";

li["Modified By"] = "4";

li.Update();

}

}

// delay

System.Console.In.ReadLine();

}

}

}

February 21, 2008 4:01 PM
 

piet said:

ok

May 28, 2008 3:48 AM
 

John Wells said:

I am a newbie.

Need to do this sort of thing, too.

But could someone just tell me what kind of code this is and where it is run?

Thanks.

June 6, 2008 11:06 AM
 

Ace said:

my main problem is impersonation. I can run the application using default credintial from the server it self or from my machine when run locally. but when I try to access the -server/app from my machine I get 401 unauthorized error! i tried hardcoding my credintail (username, pass & domain) & it worked. I need to do that automatically based on the permission set on the document library ?!? HELP ME PLEASE >>>

June 11, 2008 3:45 AM
 

Carlos Vigo said:

To Jason, who said:

"files.Add() - there are 3 overideable(sic) method and none take 4 parameter. help"

You need to upgrade to .NET 3.0 in order to use the Add method with a Hashtable. In 2.0 it won't work.

July 4, 2008 9:27 AM
 

Michael Baltaks said:

In case it helps anyone, I've published a much more complete usable SharePoint migration tool at sourceforge.net/.../splistcp. Full source code is live in Subversion there.

July 7, 2008 8:01 PM
 

Anil Madan said:

I could not find the code at

In case it helps anyone, I've published a much more complete usable SharePoint migration tool at sourceforge.net/.../splistcp. Full source code is live in Subversion there.

If possible could you send me the code

Thanks

Anil

AnilM@ForBizTech.com

August 15, 2008 10:45 AM

Leave a Comment

(required )  
(optional )
(required )  
Add

Need SharePoint Training? Attend a SharePoint Bootcamp!

Posts (c) their respective authors. Everything else (c) 2007 SharePoint Experts