Upload files to SharePoint 2010 using PowerShell or C#

I had a need to upload an XML file to a SharePoint 2010 library.  Here’s how I finally got it to work:

PowerShell

 

$destinationurl = "https://my.sharepointserver.com/sites/my-site-name/my-doc-library/my-folder/filename.xml"

$sourceurl = "c:\temp\filename.xml"

$wc = new-object system.net.webclient
[byte[]] $response = $wc.uploadfile($destinationurl, "PUT", $sourceurl)

 

I’m afraid it doesn’t provide much in the way of validation, but it works.  Here’s the same thing in C#, but which takes the source and destination urls as arguments. Obviously the PowerShell approach could be wrapped up in a script that does the same thing.  Sorry about the formatting. I’m really not digging this blog theme.  I need to change it.

C#

 

using System;
using System.Net;

namespace spcopy
{
    class Program
    {
        static void Main(string[] args)
        { 

  // Set the local file
            //string sourceUrl = @"C:\test.txt";
            string sourceUrl = args[0];

            // Set destination file
            //string destinationUrl = @"https://my.sharepointserver.com/sites/my-site-name/my-doc-library/my-folder/filename.xml"
            string destinationUrl = args[1];

            WebClient wc = new WebClient();
            wc.UseDefaultCredentials = true;
            byte[] response = wc.UploadFile(destinationUrl, "PUT", sourceUrl);

            sourceUrl = null;
            destinationUrl = null;
            wc.Dispose();
            response = null;

            GC.Collect();
        }
    }
}

Advertisements
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: