Click here to Skip to main content
15,885,032 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This code can create directory and sub-directory. It can also upload image..The problem is I want to upload the image into sub directory, It cannot save into sub-directory.It stores only on the main directory.The main directory is the Albums directory. The concept of this, is that everytime I create a directory (that is a sub-directory), I upload images/photo that would automatically save in the directory i created..

Anyone help me regarding this matter.

ASP.NET
<pre lang="xml"><head runat="server">
    <title>Upload Image</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <br /><br />
        <asp:Button ID="Button1" runat="server" Text="Create New Directory"
            onclick="Button1_Click" />
        <br /><br />
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label> <br /> <br />

        <asp:Label ID="lblFolderName" runat="server" Text="Folder Name"></asp:Label>
        <asp:TextBox ID="txtFolderName" runat="server"></asp:TextBox> <br /><br />


        <asp:Label ID="lblUploadPhoto" runat="server" Text="Upload Photo" style="margin-left:80px"></asp:Label> <br />
        <asp:Image ID="imgPhoto" runat="server" Width="100px" Height="80px" style="margin-left:80px"/> <br />
        <asp:FileUpload ID="fileUpload" runat="server" style="margin-left:80px"/> <br /> <br />

        <asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" style="margin-left:80px" /> <br /> <br />

        
    </div>
    </form>
</body>
</html>



using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.IO; 

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        lblFolderName.Visible = false;
        txtFolderName.Visible = false;
        btnSave.Visible = false;
    }

    private void CreateDirectoryIfNotExists(string NewDirectory)
    {
        try
        {
            // Checking the existance of directory
            if (!Directory.Exists(NewDirectory))
            {
                //If No any such directory then creates the new one
                Directory.CreateDirectory(NewDirectory);
                Label1.Text = &quot;Directory Created&quot;;
            }
            else
            {
                Label1.Text = &quot;Directory Exist&quot;;
            }
        }
        catch (IOException _err)
        {
            Response.Write(_err.Message);
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        lblFolderName.Visible = true;
        txtFolderName.Visible = true;
        btnSave.Visible=true;
        Label1.Visible = false;


    }
    protected void btnSave_Click(object sender, EventArgs e)
    {


        string NewDirectory = Server.MapPath(&quot;~/Albums/&quot; + txtFolderName.Text);
        //New Directory Name in string variable
        CreateDirectoryIfNotExists(NewDirectory);
        //Calling the function to create new directory
        Label1.Visible = true;
    }
}
Posted
Updated 24-Sep-13 9:33am
v2

 
Share this answer
 
Comments
brighteyes24 24-Sep-13 16:43pm    
i tried that already. I had read already that article..but still not working..
Dholakiya Ankit 25-Sep-13 0:19am    
The code you have provided is only for the creating directory where you are saving image
brighteyes24 25-Sep-13 7:34am    
yah your right. the codes show creating directory and sub-directory..the image also save into main directory (Albums directory).My question is how to save the image into sub-directory..maybe there is lack in my codes..need to modified or whatever..
Dholakiya Ankit 25-Sep-13 7:46am    
But is very simple solution you have to try for that one so follow as under :-
1. Check subdirectory is creating
2. Save image into that one
3. And then post code then we can help you better
brighteyes24 25-Sep-13 7:52am    
ok..i will send the codes..complete..
XML
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Upload Image</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <br /><br />
        <asp:Button ID="Button1" runat="server" Text="Create New Directory"
            onclick="Button1_Click" />
        <br /><br />
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label> <br /> <br />

        <asp:Label ID="lblFolderName" runat="server" Text="Folder Name"></asp:Label>
        <asp:TextBox ID="txtFolderName" runat="server"></asp:TextBox> <br /><br />


        <asp:Label ID="lblUploadPhoto" runat="server" Text="Upload Photo" style="margin-left:80px"></asp:Label> <br />
        <asp:Image ID="imgPhoto" runat="server" Width="100px" Height="80px" style="margin-left:80px"/> <br />
        <asp:FileUpload ID="fileUpload" runat="server" style="margin-left:80px"/> <br /> <br />

        <asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" style="margin-left:80px" /> <br /> <br />

    </div>
    </form>
</body>
</html>




C#
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.IO; //additional namespace is required for io operations
using System.Data.SqlClient;
using System.Data.SqlTypes;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        lblFolderName.Visible = false;
        txtFolderName.Visible = false;
        btnSave.Visible = false;
    }

    private void CreateDirectoryIfNotExists(string NewDirectory)
    {
        try
        {
            // Checking the existance of directory
            if (!Directory.Exists(NewDirectory))
            {
                //If No any such directory then creates the new one
                Directory.CreateDirectory(NewDirectory);
                Label1.Text = "Directory Created";
            }
            else
            {
                Label1.Text = "Directory Exist";
            }
        }
        catch (IOException _err)
        {
            Response.Write(_err.Message);
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        lblFolderName.Visible = true;
        txtFolderName.Visible = true;
        btnSave.Visible=true;
        Label1.Visible = false;
          
        
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
           
       
        string NewDirectory = Server.MapPath("~/Albums/" + txtFolderName.Text);
        //New Directory Name in string variable
        CreateDirectoryIfNotExists(NewDirectory);
        //Calling the function to create new directory
        Label1.Visible = true;
        
        FileUpload img = (FileUpload)fileUpload;
        Byte[] imgByte = null;
        if (img.HasFile && img.PostedFile != null)
        {
            //To create a PostedFile
            HttpPostedFile File = fileUpload.PostedFile;
            //Create byte Array with file len
            imgByte = new Byte[File.ContentLength];
            //force the control to load data in array
            File.InputStream.Read(imgByte, 0, File.ContentLength);
        

            // Insert the profile records into db
            string conn = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
            //string conn = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Coldwind.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
            SqlConnection connection = new SqlConnection(conn);
            // SqlDataReader dr = new SqlDataReader();
            string fname = fileUpload.FileName.ToString();
            string FolderName = txtFolderName.Text.Replace("'", "''");
           
            

            connection.Open();
            string sql = "INSERT INTO [ImageTable]([FolderName],[PhotoFileName]) Values('" + FolderName + "','" + fname.ToString() + "' )";
            SqlCommand cmd = new SqlCommand(sql, connection);
            cmd.CommandType = CommandType.Text;

            cmd.ExecuteNonQuery();
            connection.Close();
            imgPhoto.Visible = true;
            StartUpLoad();
             
        }
        else
        {
            Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('Please select a photo before creating a profile')", true);

        }
    }


    private void StartUpLoad()
    {
        //get the file name of the posted image
        string imgName = fileUpload.FileName;
        //sets the image path
        string subfolder = txtFolderName.Text;
        string imgPath = "~/Albums/" + subfolder + imgName;
        //get the size in bytes that
        int imgSize = fileUpload.PostedFile.ContentLength;

       

        //validates the posted file before saving
        if (fileUpload.PostedFile != null && fileUpload.PostedFile.FileName != "")
        {
            // 10240 KB means 10MB, You can change the value based on your requirement
            if (fileUpload.PostedFile.ContentLength > 10240000)
            {
                Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('File is too big.')", true);
            }
            else
            {
                //then save it to the Folder
                fileUpload.SaveAs(Server.MapPath(imgPath));
                imgPhoto.ImageUrl = "~/" + imgPath;
                Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('Profile Photo has been uploaded!')", true);
            }

        }
    }
}
 
Share this answer
 
v2
Comments
Dholakiya Ankit 26-Sep-13 0:34am    
string imgPath = "~/Albums/" + subfolder "/" + imgName;
brighteyes24 26-Sep-13 7:45am    
thank you.. I got it now.. you given me idea.. the correct codes is String imgPath="~/Albums" + subfolder + "/" + imgName; you lack positive(+) operator..but anyway (Y) thank you..I can proceed now to my project..You save my life..you solve my problem..thank you once again.. your'e my idol..more power to you..
Dholakiya Ankit 26-Sep-13 8:00am    
Oh ! Man Welcome

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900