Create,Delete,Copy Folder in ASP.NET Core 2.1

Nay mình làm một ví dụ về cách Create,Delete,Copy Folder in ASP.NET Core 2.1. Thông thường nếu bạn có làm một project về upload file hay gì đó lên một thư mục, thì ta rất cần các chức năng này

# Create Project ASP.NET Core 2.1

Bước 1: Trong Visual Studio 2019, Bạn chọn File->New, chọn Project
Bước 2: Chọn Create a new project
Bước 3: Chọn ASP.NET Core Web Application template
Bước 4: Đặt tên Project, chọn Create. 
Bước 5: Select .NET Core, ASP.NET Core 2.1, Chọn Web Application (Model-View-Controller), Create

# Create Folder in ASP.NET Core 2.1

Đầu tiên sau khi tạo xong Project bạn vào Views/Home/Index.cshtml mở file lên và xóa hết code trong đó và sửa lại như code dưới đây, bời vì ta cần viết giao diện lại cho nó

<div class="row">
        <div class="col-md-12">
            @{
                var success = ViewBag.success;
                if (success == 0)
                {
                    <h1>Không thành công!</h1>
                }
                if (success == 1)
                {
                    <h1>Thao tác thực hiện thành công!</h1>
                }
            }
        </div>
        <div class="col-md-4">
            <h1>Create Folder</h1>
            <form asp-controller="Home" asp-action="CreateFolder">
                @Html.AntiForgeryToken()
                <input type="text" name="foldername" class="form-control" />
                <input type="submit" name="submit" value="Create" class="btn btn-primary" />
            </form>
        </div>
     </div>
</div>

Trong đoạn code trên ta tạo một cái form có asp-controller="Home" asp-action="CreateFolder" dùng để submit đến hàm trong file HomeController.cs của ta
ViewBag.success: dùng để kiểm tra việc ta có thực hiện thao tác thành công hay là thất bại
Ok giờ bạn vào Controllers/HomeController.cs và chỉnh lại như đoạn code sau:

using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace CreateReadDeleteCopy.Controllers
{
    public class HomeController : Controller
    {
        private readonly IHostingEnvironment _environment;
        public HomeController(IHostingEnvironment environment)
        {
            this._environment = environment;
        }
        public IActionResult Index(int? id)
        {
            var success = id;
            ViewBag.success = success;
            //Call list Directory
            ViewBag.listDir = ReaderAllFolder();
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult CreateFolder(IFormCollection collection)
        {
                if (ModelState.IsValid)
                {
                    string foldername = collection["foldername"];
                    if (foldername != "")
                    {
                        //wwwwroot
                        string path = this._environment.WebRootPath;
                        //get list folder in wwwroot
                        var listDir = Directory.GetDirectories(path);
                        string absolutePath = Path.GetFullPath(path);
                        string stringPath = Path.Combine(absolutePath, foldername);
                        //check fordername in wwwroot directory
                        var check = listDir.Where(s => s.Equals(stringPath)).Count();
                        if (check > 0)
                        {
                            return RedirectToAction("Index", "Home", new { id = 0 });
                        }
                       
                        Directory.CreateDirectory(stringPath);
                        return RedirectToAction("Index", "Home", new { id = 1 });
                    }
                    return RedirectToAction("Index", "Home", new { id = 0 });

                }
                return RedirectToAction("Index", "Home", new { id = 0 });
        }
         /*Read Directory wwwRoot*/
        public IEnumerable<string> ReaderAllFolder()
        {
            var listFolder = Directory.GetDirectories(this._environment.WebRootPath);
            return listFolder;
        }
    }
}

Trong đoạn code trên các bạn cần thêm một số thư viện vào như sau:
+ using System.IO: dùng để gọi các hàm xử lý file
+ using Microsoft.AspNetCore.Hosting : dùng để giúp ta cài đặt IHostingEnvironment gọi tới thư mục root của hệ thống
+ using Microsoft.AspNetCore.Http : giúp ta nhận dữ liệu từ form gửi qua Controller để xử lý, Tôi có dùng (IFormCollection) trong hàm CreateFolder bạn xem ở bên trên
Với đoạn mã trên bạn sẽ thấy một vài câu lệnh xử lý như sau:
+ ReaderAllFolder(): lấy tất cả folder trong đường dẫn cụ thể
+ this._environment.WebRootPath: lấy đường dẫn thư mục wwwroot
+ Directory.GetDirectories(path) : Lấy toàn bộ thư mục trong một đường dẫn củ thể
+ Path.Combine() : chúng ta chèn  path & name folder, để nối thành một đường dẫn cự thể trỏ tới thư mục đích
+ Directory.CreateDirectory(stringPath): Để tạo được thư mục, ta cần kiểm tra xem, trong đường dẫn cần tạo có folder đó chưa, chưa có ta sẽ tạo nó

# Delete Folder in ASP.NET Core 2.1

Tại file Index.cshtml trong thư mục Views/Home/Index.cshtml ta code thêm một form xử lý Delete folder như sau

<div class="col-md-4">
            <h1>Delete Folder</h1>
            <form asp-controller="Home" asp-action="DeleteFolder">
                @Html.AntiForgeryToken()
                <select class="form-control" name="foldername">
                    @foreach (var dir in ViewBag.listDir)
                    {

                        <option value="@dir">@dir</option>
                    }
                </select>
                <input type="submit" name="submit" value="Create" class="btn btn-primary" />
            </form>
</div>

Hiển thị danh sách thư mục ra select option, sao đó select thư mục cần xóa gửi tới action="DeleteFolder" trong HomeController.cs
OK, giờ mở file HomeController.cs lên thiết lặp cái action DeleteFolder 

/*Delete Directory*/
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult DeleteFolder(IFormCollection collection)
        {
            if (ModelState.IsValid)
            {
                string path = collection["foldername"];
                if (Directory.Exists($@"{path}"))
                {
                    Directory.Delete($@"{path}");
                    return RedirectToAction("Index", "Home", new { id = 1 });
                }
                return RedirectToAction("Index", "Home", new { id = 0 });
            }
            return RedirectToAction("Index", "Home", new { id = 0 });
        }

Bạn thấy đấy, với đoạn mã trên, ta cần kiểm tra form có được Submit hay chưa bằng ModelState.IsValid
Ok, tiếp theo là kiểm tra thư mục có tồn tại hay không, nếu có ta sẽ delete nó, rồi return về Index kèm theo id=1, nếu thành công!

# Copy Folder in ASP.NET Core 2.1

Mở Index.cshtml lên và cái đặt thêm một form để xử lý việc copy folder như sau:

<div class="col-md-4">
            <h1>Copy Folder</h1>
            <form asp-controller="Home" asp-action="CopyFolder">
                @Html.AntiForgeryToken()
                <div class="form-group">
                    <label>From Fodler</label>
                    <select class="form-control" name="fromFolder">
                        @foreach (var dir in ViewBag.listDir)
                        {
                            <option value="@dir">@dir</option>
                        }
                    </select>
                </div>
                <div class="form-group">
                    <label>To Folder</label>
                    <select class="form-control" name="toFolder">
                        @foreach (var dir in ViewBag.listDir)
                        {

                            <option value="@dir">@dir</option>
                        }
                    </select>
                </div>
                <input type="submit" name="submit" value="Copy Folder" class="btn btn-primary" />
            </form>
        </div>

Bạn hiển thị danh sách thư mục ra select option và chọn nó thôi, giá trị (fromFolder & toFolder) send tới action="CopyFolder" trong file HomeController.cs để xử lý nó
Mở file HomeController.cs lên thêm action CopyFolder vào như sau:

/*Copy Folder*/
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult CopyFolder(IFormCollection collection)
        {
            if (ModelState.IsValid)
            {
                string fromFolder = collection["fromFolder"];
                string toFolder = collection["toFolder"];
                DirectoryCopy(fromFolder, toFolder, true);
                return RedirectToAction("Index", "Home", new { id = 1 });
            }
            return RedirectToAction("Index", "Home",new { id = 0});
        }
        private static void DirectoryCopy(string CopyFromFolder, string CopyToFolder, bool copySubDirs)
        {

            DirectoryInfo dir = new DirectoryInfo(CopyFromFolder);
         //   DirectoryInfo[] dirs = dir.GetDirectories();
            if (!dir.Exists)
            {
                throw new DirectoryNotFoundException(
                    "Đường dẫn không tồn tại "
                    + CopyFromFolder);
            }
            if (!Directory.Exists(CopyToFolder))
            {
                Directory.CreateDirectory(CopyToFolder);
            }
            // Lấy file trong thư mục, và copy tới đường dẫn mới
            FileInfo[] files = dir.GetFiles();
            foreach (FileInfo file in files)
            {
                string temppath = Path.Combine(CopyToFolder, file.Name);

              //  if (Directory.Exists(temppath))
              //  {
                   // Directory.Delete(temppath);
               // }
               //true cho phép ghi đè, ngược lại false
                file.CopyTo(temppath, true);
            }

            string[] folders = Directory.GetDirectories(CopyFromFolder);

            foreach (string folder in folders)

            {

                string name = Path.GetFileName(folder);

                string dest = Path.Combine(CopyToFolder, name);

                DirectoryCopy(folder, dest,true);

            }
            

        }

Đoạn code trên bạn thấy như sau:
+ Kiểm tra tồn tại của đường dẫn thư mục toFolder
+ Copy file trong thư mục(fromFolder), đến thư mục mới(toFolder)
+ Copy folder trong thư mục(fromFolder), đến thư mục mới(toFolder)
+ DirectoryCopy(folder, dest,true); viết hàm dùng để gọi lấy hết dữ liệu trong thư mục

#Read Folder in ASP.NET Core 2.1

Mở file Index.cshtml lên thêm code sao, để hiển thị thư mục trong đường dẫn

<div class="col-md-4">
            <h1>List Folder</h1>
            <ul>
                @foreach (var dir in ViewBag.listDir)
                {
                    <li>@dir</li>
                }

            </ul>
</div>

Ok, vậy là xong rồi, bạn có thể chạy thư

FullCode Index.cshtml

@{
    ViewData["Title"] = "Home Page";
}

    <div class="row">
        <div class="col-md-12">
            @{
                var success = ViewBag.success;
                if (success == 0)
                {
                    <h1>Không thành công!</h1>
                }
                if (success == 1)
                {
                    <h1>Thao tác thực hiện thành công!</h1>
                }
            }
        </div>
        <div class="col-md-4">
            <h1>Create Folder</h1>
            <form asp-controller="Home" asp-action="CreateFolder">
                @Html.AntiForgeryToken()
                <input type="text" name="foldername" class="form-control" />
                <input type="submit" name="submit" value="Create" class="btn btn-primary" />
            </form>
        </div>
        <div class="col-md-4">
            <h1>Delete Folder</h1>
            <form asp-controller="Home" asp-action="DeleteFolder">
                @Html.AntiForgeryToken()
                <select class="form-control" name="foldername">
                    @foreach (var dir in ViewBag.listDir)
                    {

                        <option value="@dir">@dir</option>
                    }
                </select>
                <input type="submit" name="submit" value="Create" class="btn btn-primary" />
            </form>
        </div>
        <div class="col-md-4">
            <h1>Copy Folder</h1>
            <form asp-controller="Home" asp-action="CopyFolder">
                @Html.AntiForgeryToken()
                <div class="form-group">
                    <label>From Fodler</label>
                    <select class="form-control" name="fromFolder">
                        @foreach (var dir in ViewBag.listDir)
                        {
                            <option value="@dir">@dir</option>
                        }
                    </select>
                </div>
                <div class="form-group">
                    <label>To Folder</label>
                    <select class="form-control" name="toFolder">
                        @foreach (var dir in ViewBag.listDir)
                        {

                            <option value="@dir">@dir</option>
                        }
                    </select>
                </div>
                <input type="submit" name="submit" value="Copy Folder" class="btn btn-primary" />
            </form>
        </div>
        <div class="col-md-4">
            <h1>List Folder</h1>
            <ul>
                @foreach (var dir in ViewBag.listDir)
                {
                    <li>@dir</li>
                }

            </ul>
        </div>
    </div>

FullCode HomeController.cs

using System;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace CreateReadDeleteCopy.Controllers
{
    public class HomeController : Controller
    {
        private readonly IHostingEnvironment _environment;
        public HomeController(IHostingEnvironment environment)
        {
            this._environment = environment;
        }
        public IActionResult Index(int? id)
        {
            var success = id;
            ViewBag.success = success;
            //Call list Directory
            ViewBag.listDir = ReaderAllFolder();
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult CreateFolder(IFormCollection collection)
        {
                if (ModelState.IsValid)
                {
                    string foldername = collection["foldername"];
                    if (foldername != "")
                    {
                        //wwwwroot
                        string path = this._environment.WebRootPath;
                        //get list folder in wwwroot
                        var listDir = Directory.GetDirectories(path);
                        string absolutePath = Path.GetFullPath(path);
                        string stringPath = Path.Combine(absolutePath, foldername);
                        //check fordername in wwwroot directory
                        var check = listDir.Where(s => s.Equals(stringPath)).Count();
                        if (check > 0)
                        {
                            return RedirectToAction("Index", "Home", new { id = 0 });
                        }
                       
                        Directory.CreateDirectory(stringPath);
                        return RedirectToAction("Index", "Home", new { id = 1 });
                    }
                    return RedirectToAction("Index", "Home", new { id = 0 });

                }
                return RedirectToAction("Index", "Home", new { id = 0 });
        }

        /*Read Directory wwwRoot*/
        public IEnumerable<string> ReaderAllFolder()
        {
            var listFolder = Directory.GetDirectories(this._environment.WebRootPath);
            return listFolder;
        }
        
        /*Delete Directory*/
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult DeleteFolder(IFormCollection collection)
        {
            if (ModelState.IsValid)
            {
                string path = collection["foldername"];
                if (Directory.Exists($@"{path}"))
                {
                    Directory.Delete($@"{path}");
                    return RedirectToAction("Index", "Home", new { id = 1 });
                }
                return RedirectToAction("Index", "Home", new { id = 0 });
            }
            return RedirectToAction("Index", "Home", new { id = 0 });
        }

        /*Copy Folder*/
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult CopyFolder(IFormCollection collection)
        {
            if (ModelState.IsValid)
            {
                string fromFolder = collection["fromFolder"];
                string toFolder = collection["toFolder"];
                DirectoryCopy(fromFolder, toFolder, true);
                return RedirectToAction("Index", "Home", new { id = 1 });
            }
            return RedirectToAction("Index", "Home",new { id = 0});
        }
        private static void DirectoryCopy(string CopyFromFolder, string CopyToFolder, bool copySubDirs)
        {

            DirectoryInfo dir = new DirectoryInfo(CopyFromFolder);
         //   DirectoryInfo[] dirs = dir.GetDirectories();
            if (!dir.Exists)
            {
                throw new DirectoryNotFoundException(
                    "Đường dẫn không tồn tại "
                    + CopyFromFolder);
            }
            if (!Directory.Exists(CopyToFolder))
            {
                Directory.CreateDirectory(CopyToFolder);
            }
            // Lấy file trong thư mục, và copy tới đường dẫn mới
            FileInfo[] files = dir.GetFiles();
            foreach (FileInfo file in files)
            {
                string temppath = Path.Combine(CopyToFolder, file.Name);

              //  if (Directory.Exists(temppath))
              //  {
                   // Directory.Delete(temppath);
               // }
               //true cho phép ghi đè, ngược lại false
                file.CopyTo(temppath, true);
            }

            string[] folders = Directory.GetDirectories(CopyFromFolder);

            foreach (string folder in folders)

            {

                string name = Path.GetFileName(folder);

                string dest = Path.Combine(CopyToFolder, name);

                DirectoryCopy(folder, dest,true);

            }
            

        }
    }
}
Create,Delete,Copy Folder in ASP.NET Core 2.1

 

Bài Viết Liên Quan

Messsage

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)