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 chúng tôi 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:
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(); chúng tôi += new EventHandler(FileAndDirectoryForm_Load); } private void FileAndDirectoryForm_Load(object sender, EventArgs e) { try { string directoryPath = "StoredFiles"; if (!System.IO.Directory.Exists(directoryPath)) System.IO.Directory.CreateDirectory(directoryPath); string filePath = directoryPath + @"EmployeeList.txt"; System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Create); 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()); } } } }