News Ticker

Menu

Tự động tạo thư mục theo thời gian để lưu trữ trong Asp.net

(Automatically Create folders or Directory files In Asp.net) – Đối với các thư mục lưu trữ file, nếu không được quy hoạch và đặt tên theo quy chuẩn thì theo thời gian file sẽ nhiều lên lúc đó việc tìm kiếm sẽ gặp nhiều khó khăn. Đặc biệt là việc lưu trữ các file trên Server được Upload từ phía người dùng. Bài viết dưới đây sẽ hướng dẫn các bạn 1 cách để lưu trữ file một cách khoa học, đó là việc tự động tạo ra các thư mục theo năm, theo tháng. Mỗi khi người dùng Upload file chương trình sẽ tự động kiểm tra xem đã tồn tại thư mục đó chưa, nếu chưa có thì tạo thư mục mới và Upload file vào thư mục đó. Và nếu có thư mục đó rồi thì chỉ thực hiện công việc Upload file thôi.


Xem những Video hay dành cho thiếu nhi - Nghe trên Youtube



Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET


B1: Tạo Project trong Microsoft Visual Studio 2010

B2: Mở file Default.aspx dưới dạng HTML và  nhập mã HTML
C# Code
<%@ Page Title="Automatically Create Folder in Asp.Net" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="AutomaticallyCreateFolder._Default" %>

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <table cellpadding="3" cellspacing="5" border="0" width="50%">
        <tr>
            <td>
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <asp:label id="lblHeader" runat="server" Text="File Upload"></asp:label>
                    </div>
                    <div class="panel-body">
                        <table cellspacing="2" cellpadding="3" border="0" width="100%">
                            <tr>
                                <td style="width:25%;">
                                    <asp:label id="plFileName" runat="server" Text="File Name (*)"></asp:label>
                                </td>
                                <td>
                                    <asp:FileUpload ID="FileUpload" runat="server" Width="150px" /><br />
                                    <asp:CustomValidator id="valFile" runat="server" CssClass="NormalRed" ValidationGroup="validate" OnServerValidate="valFile_ServerValidate" ErrorMessage="You Must Upload A File" Display="Dynamic"></asp:CustomValidator>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="2">
                                    <asp:label id="lblMessage" runat="server" Visible="false"></asp:label><br />
                                </td>
                            </tr>
                        </table>
                    </div>
                    <div class="modal-footer">
                        <div class="btn-group">
                            <asp:LinkButton id="cmdUpload" runat="server" CssClass="btn btn-small" OnClick="cmdUpload_Click" ValidationGroup="validate" Causesvalidation="true">
                                <i class="icon-upload"></i>&nbsp;&nbsp;<asp:label id="lblUpload" runat="server" Text="Upload"></asp:label>
                            </asp:LinkButton>
                        </div>
                    </div>
                </div>
            </td>
        </tr>       
    </table>
</asp:Content>
VB.Net Code
<%@ Page Title="Automatically Create Folder in Asp.Net" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="AutomaticallyCreateFolder._Default" %>

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <table cellpadding="3" cellspacing="5" border="0" width="50%">
        <tr>
            <td>
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <asp:label id="lblHeader" runat="server" Text="File Upload"></asp:label>
                    </div>
                    <div class="panel-body">
                        <table cellspacing="2" cellpadding="3" border="0" width="100%">
                            <tr>
                                <td style="width:25%;">
                                    <asp:label id="plFileName" runat="server" Text="File Name (*)"></asp:label>
                                </td>
                                <td>
                                    <asp:FileUpload ID="FileUpload" runat="server" Width="150px" /><br />
                                    <asp:CustomValidator id="valFile" runat="server" CssClass="NormalRed" ValidationGroup="validate" ErrorMessage="You Must Upload A File" Display="Dynamic"></asp:CustomValidator>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="2">
                                    <asp:label id="lblMessage" runat="server" Visible="false"></asp:label><br />
                                </td>
                            </tr>
                        </table>
                    </div>
                    <div class="modal-footer">
                        <div class="btn-group">
                            <asp:LinkButton id="cmdUpload" runat="server" CssClass="btn btn-small" ValidationGroup="validate" Causesvalidation="true">
                                <i class="icon-upload"></i>&nbsp;&nbsp;<asp:label id="lblUpload" runat="server" Text="Upload"></asp:label>
                            </asp:LinkButton>
                        </div>
                    </div>
                </div>
            </td>
        </tr>       
    </table>
</asp:Content>

B3: Viết Code cho file Default.aspx
C# Code
//Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Diagnostics;
using System.Web.UI;
using System.Web;
using System.Web.UI.WebControls;

namespace AutomaticallyCreateFolder
{

    public partial class _Default : System.Web.UI.Page
    {

        #region "Private Members"

        string FilePath = "";

        #endregion

        #region "Private Methods"

        protected string UploadFile(FileUpload file)
        {
            string fileName = null;
            string fileExtension = null;
            string strDate = DateTime.Now.ToString("MM_dd_yyyy_hh_mm_ss");

            SetFilePath();

            fileExtension = Path.GetExtension(file.FileName).Replace(".", "");
            fileName = file.FileName.Substring(file.FileName.LastIndexOf("\\\\") + 1);
            fileName = fileName.Substring(0, fileName.LastIndexOf(fileExtension)) + strDate + "." + fileExtension;

            FilePath = FilePath + fileName;
            file.SaveAs(FilePath);
            return fileName;
        }

        private void SetFilePath()
        {
            FilePath = MapPath("~/Upload/") + "/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/";
            //Create Folder
            if (!Directory.Exists(FilePath))
            {
                Directory.CreateDirectory(FilePath);
            }
        }

        #endregion

        #region "Event Handles"

        protected void cmdUpload_Click(object sender, System.EventArgs e)
        {
            if (Page.IsValid)
            {
                try
                {
                    string sFileName = "";
                    if (!string.IsNullOrEmpty(FileUpload.PostedFile.FileName))
                    {
                        sFileName = UploadFile(FileUpload);
                    }
                }
                catch
                {
                    lblMessage.Text = "Upload file Error";
                    lblMessage.ForeColor = System.Drawing.Color.Red;
                    lblMessage.Visible = true;
                }
                finally
                {
                    lblMessage.Text = "Upload file Sucessfully";
                    lblMessage.ForeColor = System.Drawing.Color.Green;
                    lblMessage.Visible = true;
                }
            }
        }

        protected void valFile_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (FileUpload.PostedFile != null)
            {
                if (FileUpload.PostedFile.ContentLength > 0)
                {
                    args.IsValid = true;
                }
                else
                {
                    args.IsValid = false;
                }
            }
        }

        #endregion
    }
}
VB.Net Code

'Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
Imports System.IO

Namespace AutomaticallyCreateFolder

    Public Class _Default
        Inherits System.Web.UI.Page

#Region "Private Members"

        Private FilePath As String = ""

#End Region

#Region "Private Methods"

        Protected Function UploadFile(ByVal file As FileUpload) As String
            Dim fileName As String
            Dim fileExtension As String
            Dim strDate As String = Now.ToString("MM_dd_yyyy_hh_mm_ss")

            SetFilePath()

            fileExtension = Replace(Path.GetExtension(file.FileName), ".", "")
            fileName = file.FileName.Substring(file.FileName.LastIndexOf("\\") + 1)
            fileName = fileName.Substring(0, fileName.LastIndexOf(fileExtension)) & strDate & "." & fileExtension

            FilePath = FilePath + fileName
            file.SaveAs(FilePath)
            Return fileName
        End Function

        Private Sub SetFilePath()
            FilePath = MapPath("~/Upload/") & "/" & Now.Year & "/" & Now.Month & "/"
            'Create Folder
            If Not Directory.Exists(FilePath) Then
                Directory.CreateDirectory(FilePath)
            End If
        End Sub

#End Region

#Region "Event Handles"

        Private Sub cmdUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdUpload.Click
            If Page.IsValid Then
                Try
                    Dim sFileName As String = ""
                    If FileUpload.PostedFile.FileName <> "" Then
                        sFileName = UploadFile(FileUpload)
                    End If
                Catch ex As Exception
                    lblMessage.Text = ex.Message
                    lblMessage.ForeColor = System.Drawing.Color.Red
                    lblMessage.Visible = True
                    Exit Sub
                Finally
                    lblMessage.Text = "Upload file Sucessfully"
                    lblMessage.ForeColor = System.Drawing.Color.Green
                    lblMessage.Visible = True
                End Try
            End If
        End Sub

        Private Sub valFile_ServerValidate(ByVal source As System.Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles valFile.ServerValidate
            Try
                If Not (FileUpload.PostedFile Is Nothing) Then
                    If (FileUpload.PostedFile.ContentLength > 0) Then
                        args.IsValid = True
                        Return
                    End If
                End If
                args.IsValid = False
            Catch exc As Exception

            End Try
        End Sub

#End Region

    End Class

End Namespace
Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET




Chúc các bạn thành công!

Quang Bình

Share This:

Post Tags:

Mỗi bài viết đều là công sức và thời gian của tác giả ví vậy tác giả chỉ có một mong muốn duy nhất nếu ai đó có Copy thì xin hãy ghi rõ nguồn và thông tin tác giả ở cuối mỗi bài viết.
Xin cảm ơn!

No Comment to " Tự động tạo thư mục theo thời gian để lưu trữ trong Asp.net "

  • To add an Emoticons Show Icons
  • To add code Use [pre]code here[/pre]
  • To add an Image Use [img]IMAGE-URL-HERE[/img]
  • To add Youtube video just paste a video link like http://www.youtube.com/watch?v=0x_gnfpL3RM