1

I have a fileupload in my page so the user can browse the computer and select the file. After selecting the file when I want to get the name of file using this code:

string ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);

It returns null and I got this error :

Object reference not set to an instance of an object.

After debugging I found that my file is posted null and it doesn't send. Why? After adding a little code I got this error :

<asp:UpdatePanel runat="server" ID="UpdatePanel1" UpdateMode="Always">
        <ContentTemplate>
<div class="wrapper-box">
                                <div class="topbox">
                                    عکس خبر
                                </div>
                                 <asp:FileUpload ID="FileUpload1" runat="server" CssClass="text-input-two" />
                            </div>


        </ContentTemplate>
    </asp:UpdatePanel>
mkj
  • 2,761
  • 5
  • 24
  • 28
user3527150
  • 936
  • 9
  • 15
  • 2
    check if FileUpload1.PostedFile is null or not. – Manish Parakhiya Apr 23 '14 at 11:15
  • 1
    How can it return null AND throw an exception? Please be more specific: which line of code throws the exception? – helb Apr 23 '14 at 11:16
  • System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName); this line Throws an exception – user3527150 Apr 23 '14 at 11:19
  • Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Apr 23 '14 at 11:33
  • Try to check if FileUpload1.PostedFile is null, sometimes the asp:FileUpload component don't work with update panel – bdn02 Apr 23 '14 at 15:18

4 Answers4

1

According to MSDN GetExtension will only return null if you pass in a FileName that's null.

The extension of the specified path (including the period "."), or Nothing[Null], or String.Empty. If path is Nothing[Null], GetExtension returns Nothing[Null]. If path does not have extension information, GetExtension returns String.Empty.

So check if (file != null && file.FileName != null) first before proceeding furthure.

Neel
  • 11,625
  • 3
  • 43
  • 61
1

Get extension method returns a extension of file. check following code sample

string s = System.IO.Path.GetExtension("file1.aspx");

you can use FileUpload1.fileName instead of fileupload1.postedfile.filename

hope it helps

koolprasad2003
  • 299
  • 3
  • 23
0

Try adding this postback trigger between and

</ContentTemplate>
  <Triggers>
     <asp:PostBackTrigger ControlID="Button1" />
  </Triggers>
</asp:UpdatePanel>

And add enctype="multipart/form-data" to your form

<form id="form1" runat="server" enctype="multipart/form-data">
0

Use

string ext = System.IO.Path.GetExtension("FileName.ext");

Instead of

string ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);