01/10/2018, 17:17

Cách tạo tập tin (file) và thư mục (directory) trong C#

C# hỗ trợ các hàm cho phép bạn tạo thư mục (directory) và tập tin (file) khi bạn muốn. Các hàm này nằm trong namespace System.IO Hàm tạo thư mục CreateDirectory () thuộc lớp (class) Directory của namespace System.IO, cú pháp như sau: System.IO. Directory .CreateDirectory(string path); ...

C# hỗ trợ các hàm cho phép bạn tạo thư mục (directory) và tập tin (file) khi bạn muốn. Các hàm này nằm  trong namespace System.IO

Hàm tạo thư mục CreateDirectory() thuộc lớp (class) Directory của namespace System.IO, cú pháp như sau:

System.IO.Directory.CreateDirectory(string path);

Trong đó:

  • path:  là [dường dẫn +] tên thư mục bạn muốn tạo. Nếu bỏ qua [đường dẫn] thì thư mục được tạo ngay trong thư mục ứng dụng đang chạy.

Để tạo được tập tin, chúng ta phải sử dụng lớp (class) FileStream và toán tử new để tạo tập tin, cú pháp bên dưới:

System.IO.FileStream fs = new System.IO.FileStream(string path, System.IO.FileMode mode);

Trong đó:

  • path: là [đường dẫn +] tên tập tin bạn muốn tạo. Nếu bỏ qua đường dẫn thì tập tin được tạo ngay trong thư mục ứng dụng đang chạy
  • mode: dùng để thiết lập các chế độ hay tùy chọn cho tập tin được tạo như: tạo mới hoàn toàn, xóa sạch dữ liệu nếu tập tin tồn tại, thêm dữ liệu vào cuối tập tin, v.v … C# hỗ trợ các mode sau:
    • Append
    • Create
    • CreateNew
    • Open
    • OpenOrCreate
    • Truncate

Dưới đây là đoạn code viết trên VS2005, minh họa cho việc tạo thư mục & tập tin mới:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace MyProject
{
    public partial class FileAndDirectoryForm : Form
    {
        public FileAndDirectoryForm()
        {
            InitializeComponent();
            this.Load += new EventHandler(FileAndDirectoryForm_Load);
        }

        private void FileAndDirectoryForm_Load(object sender, EventArgs e)
        {
            try
            {
                // Bước 1: tạo biến để lưu thư mục cần tạo, tên thư mục cần tạo là "StoredFiles"
                string directoryPath = "StoredFiles";
                // Bước 2: kiểm tra nếu thư mục "StoredFiles" chưa tồn tại thì tạo mới
                if (!System.IO.Directory.Exists(directoryPath))
                    System.IO.Directory.CreateDirectory(directoryPath);
                // Bước 4: tạo tập tin "EmployeeList.txt" trong thư mục "StoredFiles"
                string filePath = directoryPath + @"EmployeeList.txt";
                System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Create);

                // Kết thúc: thông báo tạo tập tin thành công
                // và chỉ ra đường dẫn tập tin để người dùng dễ dàng kiểm tra tập tin vừa tạo
                string mesage = "Tạo tập tin "EmployeeList.txt" thành công." + Environment.NewLine;
                mesage += "Đường dẫn là "" + Application.StartupPath + @"" + directoryPath + filePath + """;
                MessageBox.Show(mesage, "Thông báo");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.InnerException.ToString());
            }
        }
    }
}

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


0