views:

166

answers:

2

Hi

Could you help me for how to adding a file to the sharepoint document library? I found some articles in net. but i didn't get the complete concept of the same. Now i uploaded a file without metadata by using this code.

if (fuDocument.PostedFile != null)
                {
                    if (fuDocument.PostedFile.ContentLength > 0)
                    {
                        Stream fileStream = fuDocument.PostedFile.InputStream;
                        byte[] byt = new byte[Convert.ToInt32(fuDocument.PostedFile.ContentLength)];
                        fileStream.Read(byt, 0, Convert.ToInt32(fuDocument.PostedFile.ContentLength));
                        fileStream.Close();


                        using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                        {
                            using (SPWeb webcollection = site.OpenWeb())
                            {
                                SPFolder myfolder = webcollection.Folders["My Library"];
                                webcollection.AllowUnsafeUpdates = true;
                                myfolder.Files.Add(System.IO.Path.GetFileName(fuDocument.PostedFile.FileName), byt);

                            }
                        }
                    }
                }

This code is working as fine. But i need to upload file with meta data. Please help me by editing this code if it possible. I created 3 columns in my Document library..

+2  A: 

SPFolder.Files.Add returns a SPFile object

SPFile.Item returns an SPListItem object

You can then use SPlistItem["FieldName"] to access each field (see bottom of SPListItem link)

So adding this into your code (this is not tested, but you should get the idea)

SPFile file = myfolder.Files.Add(System.IO.Path.GetFileName(document.PostedFile.FileName);
SPListItem item = file.Item;
item["My Field"] = "Some value for your field";
item.Update()
Ryan
+2  A: 

There is also an overload where you can send in a hashtable with the metadata you want to add. For example:

Hashtable metaData = new Hashtable();
metaData.Add("ContentTypeId", "some CT ID");
metaData.Add("Your Custom Field", "Your custom value");

SPFile file = library.RootFolder.Files.Add(
                    "filename.fileextension",
                    bytearray,
                    metaData,
                    false);
Johan Leino
Nice - I didn't realise you could do this, I had assumed that it was only the built in metadata fields (_vti*)
Ryan