Harold Sota
Harold Sota

Reputation: 7566

Sharepoint 2010 API upload a file with metadata creating a new version from ASP.NET web application

How I can upload a file with metadata creating a new version from ASP.NET web application to SharePoint 2010?

Is there any way?

Thanks in advance.

Upvotes: 3

Views: 1088

Answers (1)

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131601

There are multiple ways to upload a file to a document library.

Perhaps the simplest way is simply to copy the file to the document library's URL using File.Copy. SharePoint supports WebDAV so you can treat a library as a network folder, opening/saving files directly from any application, copying and renaming from Windows Explorer etc.

You do face some limitations though:

  • The full path of the file can't be larger than 260 characters and SharePoint will truncate it without warning.
  • The file name can't contain some characters that are valid for Windows Explorer, eg #
  • If you try to save a file with the same name as an existing one, SharePoint will create a new file with a slightly different name without asking
  • You have no control over the author and creation date properties. SharePoint will use the current date and the credentials of the user executing the code.
  • You can't set any metadata although you can update the file's ListItem properties after uploading.

Another option is to use the Client object model and upload the file using File.SaveBinaryDirect. This option is better than simply copying the file, as it allows you to overwrite an existing file, but you still don't get direct access to the file's properties. Uploading could be as simple as this:

var clientContext = new ClientContext("http://intranet.contoso.com");
    using (var fileStream =new FileStream("NewDocument.docx", FileMode.Open))
        ClientOM.File.SaveBinaryDirect(clientContext,
            "/Shared Documents/NewDocument.docx", fileStream, true);

Another option is to connect to a library using the Client Object Model and then create a file using FileCollection.Add, eg

Microsoft.SharePoint.Client.File uploadFile = documentsList.RootFolder.Files.Add(
fileCreationInformation);

Check this SO question, Upload a document to a SharePoint list from Client Side Object Model on how to use both SaveBinaryDirect and FileCollection.Add. The answers display both how to upload a file and how to modify its properties

Upvotes: 1

Related Questions