This sample shows how to download attached files from common business objects using the SAP tables SRGBTBREL and SOOD and the function module SO_DOCUMENT_READ_API1.
About
As of SAP rel. 4.6 users can attach documents to all common business objects, e.g., purchase orders:
This sample uses the following workflow to download attachment files:
Read the table SRGBTBREL to get all object IDs that are attached to business objects.
Read the table SOOD to get the corresponding file names and extensions of the object IDs.
Use SO_DOCUMENT_READ_API1 to download an attachment with a given object ID.
Note
The function modules BDS_CONNECTIONS_GET and BDS_DOCUMENT_GET_TABLE can not be used in this scenario. Even if BDS_CONNECTIONS_GET delivers correct document IDs, the function module BDS_DOCUMENT_GET_TABLE throws an exception (NOTHING_FOUND).
Get a List of all SAP Attachments
Get a List of Object IDs
The following sample code reads the table SRGBTBREL to obtain all document IDs attached to a business object.
The object key is the document number, e.g., the purchase number
The object type is the name of the business object, e.g., BUS2012 for POs or BUS2010 for RFQs).
The function returns an array of strings each representing a key to a downloadable attachment.
publicstaticvoidDownloadDocument(R3Connectionconnection,stringPath,stringkey){RFCFunctionfunc=connection.CreateFunction("SO_DOCUMENT_READ_API1");func.Exports["DOCUMENT_ID"].ParamValue=key;func.Execute();Int32len=Convert.ToInt32(func.Imports["DOCUMENT_DATA"].ToStructure()["DOC_SIZE"]);stringstrfile="";System.Text.Encodingenc=System.Text.Encoding.GetEncoding(1252);if(len>0){foreach(RFCStructurerowinfunc.Tables["OBJECT_CONTENT"].Rows){stringstline=row["LINE"].ToString().PadRight(255);if(len<255)stline=stline.Substring(0,len);elselen=len-255;strfile+=stline;}byte[]bytesfile=enc.GetBytes(strfile);System.IO.File.WriteAllBytes(Path,bytesfile);}else{thrownewException("Length of file = 0");}}
Read and Download Attachment Files
The following sample code queries a list of available attachments and downloads the attachments to the disk. To download attachments of other business objects, change the object type, e.g., BUS2010 for RFQ.
usingSystem;usingERPConnect;// Set your ERPConnect licenseLIC.SetLic("xxxx");usingvarconnection=newR3Connection(host:"server.acme.org",systemNumber:00,userName:"user",password:"passwd",language:"EN",client:"001"){Protocol=ClientProtocol.NWRFC,};connection.Open();string[]DocIDs=GetAllAttachmentKeys(connection,"BUS2012","4500014561");if(DocIDs.Length==0)Console.WriteLine("No attachments found");else{for(inti=0;i<DocIDs.Length;i++){stringFileName=GetFileName(connection,DocIDs[i]);Console.WriteLine("Now downloading "+FileName);DownloadDocument(connection,@"c:\"+FileName,DocIDs[i]);}}Console.WriteLine("Press enter to exit");Console.ReadLine();