2

I have the chunk of code below:

SPListItem source = //some list item;
foreach (string file in source.Attachments)
{
    SPFile oFile = source.Web.GetFile(file);
    string strFilename = oFile.Name;
    byte[] binFile = oFile.OpenBinary();  //Errors out here!
    destination.Attachments.Add(oFile.Name, binFile);
    destination.SystemUpdate();
}

Which throws this error:

EXCEPTION in CrossSiteCopy! Cannot open file "2012-05-21_104000.png". at Microsoft.SharePoint.SPGlobal.HandleComException(COMException comEx) at Microsoft.SharePoint.Library.SPRequest.GetFileAsStream(String bstrUrl, String bstrWebRelativeUrl, Boolean bHonorLevel, Byte iLevel, OpenBinaryFlags grfob, String bstrEtagNotMatch, String& pEtagNew, String& pContentTagNew) at Microsoft.SharePoint.SPFile.GetFileStreamCore(OpenBinaryFlags openOptions, String etagNotMatch, String& etagNew, String& contentTagNew) at Microsoft.SharePoint.SPFile.GetFileStream(OpenBinaryFlags openOptions, String etagNotMatch, String& etagNew, String& contentTagNew) at Microsoft.SharePoint.SPFile.OpenBinary(SPOpenBinaryOptions openOptions) at Copy_Special.CrossSiteCopy.CopyFieldValues(SPListItem source, SPListItem destination) at Copy_Special.CrossSiteCopy.<>c_DisplayClass1.b_0() at Microsoft.SharePoint.SPSecurity.<>c_DisplayClass4.b_2() at Microsoft.SharePoint.Utilities.SecurityContext.RunAsProcess(CodeToRunElevated secureCode) at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(WaitCallback secureCode, Object param) at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(CodeToRunElevated secureCode) at Copy_Special.CrossSiteCopy.Execute(ActivityExecutionContext executionContext)

It's not giving me much information about WHY it cannot open the file. Can any one point me to what the problem might be?

1
  • Can you check the SP log? Also, Can you make sure the source exists (wherever the file is)? Jun 13, 2012 at 16:03

1 Answer 1

2

You need to specify more than just the attachment file name in the SPWeb.GetFile method! Specify the Web relative file URL or the server relative file URL here. You can construct the Web relative file URL from source.Attachments.UrlPrefix + file

2
  • 1
    Instead of just using + to combine URLs you should use SPUrlUtility.CombineUrls Jun 13, 2012 at 17:56
  • Thx was not aware of this util method! Anyway, I agree and am also using my own util Url.Combine that is not so SharePoint specific. It also takes any number of string inputs for combination. Jun 14, 2012 at 7:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.