Save image using System.IO in C#


 <table>
<
tr>

<
td>
Uploaded Image
</
td>

<
td>


<
asp:FileUpload ID="fil1" runat="server"/>


</
td>

</
tr>

<
tr>

<
td colspan="2" align="center">


<
asp:Button ID="btnsubmit" runat="server" Text="Submit" CssClass="btn"
OnClientClick="StartProgressBar()"
OnClick="btnsubmit_Click"/>

</
td>

</
tr>

<
tr>

<
td colspan="2" align="center">


<
asp:Label ID="lblmessage" CssClass="lbl" runat="server"></asp:Label>


</
td>

</
tr>

</
tr>

</
table>


 

protected void btnsubmit_Click(object sender, EventArgs e)

    {

        try

        {

            HttpPostedFile Myimage;

            Myimage = fil1.PostedFile;

            if (Myimage.ContentLength == 0)

            {

                lblmessage.Text = "Please Upload Image.";

            }

            else

            {

             if (Path.GetExtension(Myimage.FileName).ToLower() == ".jpg" || Path.GetExtension(Myimage.FileName).ToLower() == ".png" || Path.GetExtension(Myimage.FileName).ToLower() == ".gif" )  

             {

                int bytesval = fil1.PostedFile.ContentLength;

                int kilobytesval = bytesval / 1024;

                System.Threading.Thread.Sleep(2000);

 

               

                fil1.PostedFile.SaveAs(@"E:\ images\" + GenerateString() + "" + Path.GetExtension(Myimage.FileName));

                lblmessage.Text = "Image saved successfully" + kilobytesval + " KB <br>";

             }

             else

             {

                 lblmessage.Text="Invalid Image Format. The Image Extension Must Be .jpg.";

             }

            }

        }

        catch (Exception ex)

        {

            lblmessage.Text = ex.ToString();

        }

    }

    public string GenerateString()

    {

        string allowedChars = "a,b,c,d,e,f,g,h,j,k,m,n,p,q,r,s,t,u,v,w,x,y,z,";

        allowedChars += "A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z,";

        allowedChars += "2,3,4,5,6,7,8,9";

        char[] sep = { ',' };

        string[] arr = allowedChars.Split(sep);

        string passwordString = "";

        string temp;

        Random rand = new Random();

        for (int i = 0; i < 6; i++)

        {

            temp = arr[rand.Next(0, arr.Length)];

            passwordString += temp;

        }

        return passwordString;

    }




Ebook Download
View all
Learn
View all