WEFX
WEFX

Reputation: 8542

Upload a file attachment for Salesforce in C#

I've seen this example to build and send an attachment to Salesforce in Java, but how is this accomplished in C#?

Edit - I'm also using this page as a reference, but I still don't know how to finish the last part where I try to create and save the attachment.

SoapClient client = new SoapClient();
LoginResult lr = client.login(new LoginScopeHeader(), username, password);

FileInfo fileInfo = new FileInfo(myFileLocation);
FileStream stream = File.OpenRead(myFileLocation);
byte[] byteArray = new byte[fileInfo.Length];
stream.Read(byteArray, 0, byteArray.Length);

Attachment attachment = new Attachment();
attachment.Body = byteArray;
attachment.Name = myFileName + ".txt";
attachment.IsPrivate = false;

SaveResult saveResult = client.create(new sObject[] { attachment })[0];

Upvotes: 1

Views: 3077

Answers (1)

Daniel Ballinger
Daniel Ballinger

Reputation: 13537

It looks correct in general. With the following changes.

After calling login, you will need to assign the resulting SessionId and ServerUrl to the client.

SoapClient client = new SoapClient();
LoginResult lr = client.login(new LoginScopeHeader(), username, password);
client.SessionHeaderValue = new SforceService.SessionHeader();
client.SessionHeaderValue.sessionId = li.sessionId;
client.Url = loginResult.serverUrl;

You should check the SaveResult to see if the record was created and what the new Id is.

//...
SaveResult saveResult = client.create(new sObject[] { attachment })[0];
if (saveResult .success){ 
    // saveResult.id contains id of newly created attachment
} else {
    //saveResult .errors[0] contains reason why attachment couldn't be created.
}

Upvotes: 1

Related Questions