In a previous article, I explained that there are 3 ways to validate data on an InfoPath form.
You can use the second method from this article to check the size of a file that has been added to a File Attachment control on an InfoPath form and report a validation error to the user if this size exceeds a predefined limit.
If you’ve added a File Attachment control named attachment to an InfoPath form template, you can add code similar to the following to the Validating event of the attachment field to programmatically restrict the size of a file that is added to the attachment field:
if (!e.UndoRedo && e.Operation == XmlOperation.ValueChange)
{
// Retrieve the attachment
string base64String = e.Site.Value;
if (!String.IsNullOrEmpty(base64String))
{
// Convert the attachment to bytes
InfoPathAttachmentDecoder decoder =
new InfoPathAttachmentDecoder(base64String);
string fileName = decoder.Filename;
byte[] data = decoder.DecodedAttachment;
// Check the file size
decimal fileSize = Math.Round(
(decimal)(data.Length / 1024F), 2);
if (fileSize > 2)
e.ReportError(e.Site, false,
String.Format(
"The size of '{0}' is {1} KB. It must be less than 2 KB.",
fileName,
fileSize.ToString()));
}
}
In the code sample above, the file size has been restricted to 2 KB. The sample also uses the InfoPathAttachmentDecoder class that is available from Microsoft.

Figure 1. Data validation error displayed on an InfoPath File Attachment control that restricts file size.
This technique can also be applied if you want to prevent users from uploading files of a particular file type using an InfoPath browser form (video).
More InfoPath File Attachment articles
How to programmatically rename an InfoPath file attachment
Learn how you can write C# code to programmatically rename a file that has been attached to an InfoPath form.
How to submit a file attached to an InfoPath form as an attachment to a SharePoint list item
Learn how you can programmatically save a file attachment from an InfoPath form as an attachment to a SharePoint list item when the InfoPath form is submitted to the SharePoint list.
How to submit an InfoPath form to a SharePoint list and attach the form to the list item
Learn how to use the Attachments collection of a SharePoint list item to save the XML of an entire InfoPath form as an attachment to a SharePoint list item.
Use a custom SharePoint workflow to extract a file attachment from an InfoPath form and upload it to a SharePoint document library
This article explains how you can use a custom Visual Studio sequential workflow on a Form Library to extract data from a File Attachment control on an InfoPath form that was submitted to the Form Library and use this data to add a file to a SharePoint Document Library.

Comments to this post were closed 30 days after it was published.