Upload an Attachment The following code example demonstrates how to upload an attachment to a note programmatically.
// Now create the annotation object.
annotation note = new annotation();
note.notetext = "This is a sample note";
note.subject = "Test Subject";
note.objectid = new Lookup();
note.objectid.type = EntityName.account.ToString();
// Sets the note's parent to the newly created account.
note.objectid.Value = createdAccountId;
note.objecttypecode = new EntityNameReference();
note.objecttypecode.Value = EntityName.account.ToString();
// Create the note.
Guid createdNoteId = service.Create(note);
#region Setup Additional Data Required for this Sample
// Now convert the attachment to be uploaded to Base64 string.
// This will create a doc file in the current folder of executable.
string currentPath = System.Environment.CurrentDirectory.ToString();
TextWriter tw = new StreamWriter(currentPath + "\\Crm" + createdNoteId.ToString() + ".doc");
// Write a line of text to the file.
tw.WriteLine("This document is for testing an attachment upload feature of CRM 4.0.");
tw.Close();
#endregion
// Open a file and read the contents into a byte array.
FileStream stream = File.OpenRead(currentPath + "\\Crm" + createdNoteId.ToString() + ".doc");
byte[] byteData = new byte[stream.Length];
stream.Read(byteData, 0, byteData.Length);
stream.Close();
// Encode the data using base64.
string encodedData = System.Convert.ToBase64String(byteData);
// Now update the note.
annotation updateNote = new annotation();
updateNote.annotationid = new Key();
// Set the Note ID that is being attached to.
updateNote.annotationid.Value = createdNoteId;
updateNote.documentbody = encodedData;
updateNote.filename = "Crm" + createdNoteId.ToString() + ".doc";
updateNote.mimetype = @"application\ms-word";
service.Update(updateNote);
Download an Attachment The following code example demonstrates how to download an attachment programmatically:
string attachid = "{61BB601D-C43F-4738-BD1F-AD22DC8E7F0E}";
string objecttypecode = "1070"; //SaleLiteratureItem
string url = "http://mycrm/Activities/Attachment/download.aspx?AttachmentType=" + objecttypecode + "&AttachmentId=" + attachid;
System.Net.WebClient myWebClient = new System.Net.WebClient();
myWebClient.Credentials = System.Net.CredentialCache.DefaultCredentials;
myWebClient.DownloadFile(url,"C:\\myfile.txt");