Sep 17

Here's a small snippet of code to upload a file from the filesystem into a SharePoint document library:

    Stream fStream = File.OpenRead("C:\\Temp\\Filename.pdf");
    byte[] contents = new byte[fStream.Length];

    fStream.Read(contents, 0, (int)fStream.Length);
    fStream.Close();

    SPList list = web.Lists[DocumentLibraryListName];
    Hashtable properties = new Hashtable();
    properties.Add("Title", "This is the title");
    properties.Add("Other_x0020_Properties", "Some other property");

    SPFile destFile = list.RootFolder.Files.Add("Filename.pdf", contents, properties, true);

    if (destFile == null)
    {
        lblError.Text = "<p>Error in adding file. Waiting to re-try.</p>";
    }

There is a free class available named DocLibHelper (search Google to download it) that would help you in uploading files among other things, but if all you need is to upload a document into a SharePoint library, then the above code will do.

Sep 14
Using C# to update windows registry
Posted by Wei in C# on 09 14th, 2009| | No Comments »

Here's the code to update the registry:

string strPath = "Software\\Path\\To\\Registry\\Location";
RegistryKey regKeyAppRoot = Registry.CurrentUser.OpenSubKey(strPath, true);
regKeyAppRoot.SetValue("Key1", "Value1");
regKeyAppRoot.SetValue("Key2", "Value2");
regKeyAppRoot.Close();

If the key doesn't exist, then you will get a null exception error: "System.NullReferenceException: Object reference not set to an instance of an object." This just means that you have to create the key before you can update it.

RegistryKey rk = Registry.CurrentUser.CreateSubKey(strPath);
rk.Close();

Initially, I thought it was a permission issue with updating the registry. So I added owner permissions to pretty much anyone and everyone. But I still got the issue. Finally figured out that all I had to do was create the Subkey. Hopefully I just saved someone hours of work.