Could you help me for how to add a file to the Sharepoint document library? I found some articles in .NET, but I didn't get the complete concept of how to accomplish this.
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 fine as is, but I need to upload a file with metadata. Please help me by editing this code if it is possible. I created 3 columns in my document library.
File system metadata includes the times recorded by the operating system when a file is modified, accessed, or created.
Metadata can be stored in a variety of places. Where the metadata relates to databases, the data is often stored in tables and fields within the database. Sometimes the metadata exists in a specialist document or database designed to store such data, called a data dictionary or metadata repository.
Metadata is created anytime a document, a file or other information asset is modified, including its deletion. Accurate metadata can be helpful in prolonging the lifespan of existing data by helping users find new ways to apply it. Metadata organizes a data object by using terms associated with that particular object.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With