Question

I recently authored a C# based script for a blog posting, which copies column data from one file to another. While testing this solution I noticed that copying this data works differently depending on the file format, which is painful to say the least.

For 'non Office 2007' files I can just assign the source file's Properties variable to the destination file. For Office 2007 files I need to write the destination file, iterate through all fields of the source file and then update the destination file again.

If I treat all documents the same then either meta data is not copied over, depending on the file type, or certain column types are not copied over (e.g. DateTime columns)

The code is as follows:

if (sourceFile.Name.EndsWith("x", StringComparison.InvariantCultureIgnoreCase) == false)
{
    // ** Pre office 2007 formats (without the trailing x) are treated differently 
    // ** from the office 2007 formats when it comes to copying meta data.
    Hashtable metadata = sourceFile.Item.Properties;
    // ** Add the file to the site including the meta data
    spDestinationFile = destinationWeb.Files.Add(destinationFilePath, convertedFile, 
                                                 metadata, true);
}
else
{
    // ** Add the file to the site.
    spDestinationFile = destinationWeb.Files.Add(destinationFilePath, 
                                                 convertedFile, null, true);
    // ** Copy the Actual meta data to the newly created file.
    foreach (SPField field in sourceFile.Item.Fields)
    {
        if (field.ReadOnlyField == false)
        {
            spDestinationFile.Item[field.Id] = sourceFile.Item[field.Id];
        }
    }
    // ** Update the meta data
    spDestinationFile.Item.Update();
}

Note that this may be related to my previous post named 'When is SPFile.Properties != to SPFile.Item.Properties in SharePoint?'

Was it helpful?

Solution 2

I am answering my own question here, but the code fragment in the question appears to be the best way to deal with copying meta data. A variant of this has been part of one of our products for 2 years and we are no longer receiving support calls about it since we changed to this logic.

OTHER TIPS

I havent run into the problem you are describing, but i got a few comments to the logic:

It seems a bit risky to just check for X at the end? (also whats with the "== false"? whats wrong with !expression ;-)

What happens if you get a non-Office 2007 extension that ends on X? Example XMX is a type of AutoCAD file. What happens when you get an Office 2007 extension that doesnt end on X? Example XLSM (macro enabled XSLX workbook).

You should probably make a whitelist to check up against containing all Office 2007 extensions.

hth Anders Rask

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top