Custom validator on file size

Hi
can anyone help with this problem, i'm trying to display an error message in a custom validator if a file size is larger than 200kbs, but i cannot get the validation to fire, i've tried changing the args,Isvalid to true or false but no luck.

Regards
George

<asp:FileUpload ID="FileUpload1" TabIndex="20" runat="server" />
                   <asp:CustomValidator ID="CustomValidator1"
                                        runat="server"
                                        ErrorMessage="File must be less than 200kb's"
                                        ControlToValidate="FileUpload1"
                                        Display="Dynamic"
                                        OnServerValidate="CustomValidator1_ServerValidate">
                  </asp:CustomValidator>

 protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
            {
            if (FileUpload1.HasFile)
                {
                System.IO.FileStream fstre = new System.IO.FileStream(FileUpload1.PostedFile.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                if (fstre.Length > 1024 * 1)//Just checking to see if file is larger than 1kb
                    {
                    args.IsValid = false;
                    CustomValidator1.Text = "File must be less than 200kb's";
                    CustomValidator1.Visible = true;
                    }
                else
                    {
                    args.IsValid = true;
                    }
                }

            }
LearningCSharpSQLAsked:
Who is Participating?
 
SimonFerrisCommented:
Here is a link to an MSDN article about FileUpload validation.

http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.fileupload.aspx

It looks like that the validation you are trying to perform cannot be done until you obtain a handle to the file. The initial control only allows you to specify the path.
0
 
SimonFerrisCommented:
Check that you have AutoWireUpEvents set to true or if this is not an option write the event handler. In C# the AutoWireUpEvents is set to true by default.
0
 
LearningCSharpSQLAuthor Commented:
Hi SimonFerris:
I have but no luck
Regards
George
0
 
SimonFerrisCommented:
0
 
LearningCSharpSQLAuthor Commented:
Thanks Simon
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.