Nếu kiểm tra tập tin,
gọi hàm theo cú pháp như sau:
System.IO.File.Exists(string path);
Trong đó: path là
đường dẫn đầy đủ và tên tập tin bạn cần kiểm tra
Nếu kiểm tra thư mục,
gọi hàm theo cú pháp như sau:
System.IO.Directory.Exists(string path);
Trong đó: path là
đường dẫn của thư mục cần kiểm tra
Ví dụ minh họa:
- Bạn cần kiểm tra tập
tin “Recruity.docx” có tồn tại trong thư mục “D:/THS/Document/HRP/Recruity/”
hay không?. Nếu tồn tại thì xuất thông báo <Tồn tại tập tin
“Recruity.docx”.>, ngược lại xuất thông báo <Không tồn tại tập tin
“Recruity.docx.”>.
- Bạn cần kiểm tra thư
mục “Recruity” có tồn tại trong thư mục “”D:/THS/Document/HRP/” hay không? Nếu
tồn tại thì xuất thông báo <Tồn tại thư mục “Recruity”.>, ngược lại xuất
thông báo <Không tồn tại thư mục “Recruity”>.
Code minh họa bên
dưới, được viết trong VS2010:
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 MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
// Gắn nút "Kiểm ta tập tin" vào form
Button btnCheckExistFile = new Button();
btnCheckExistFile.Text = "Kiểm tra tập tin";
btnCheckExistFile.Width = 150;
btnCheckExistFile.Location = new System.Drawing.Point(this.Location.X, this.Location.Y + 20);
this.Controls.Add(btnCheckExistFile);
btnCheckExistFile.Click += new EventHandler(btnCheckExistFile_Click);
// Gắn nút "Kiểm tra thư mục" vào form
Button btnCheckExistDirectory = new Button();
btnCheckExistDirectory.Text = "Kiểm tra thư mục";
btnCheckExistDirectory.Width = 150;
btnCheckExistDirectory.Location = new System.Drawing.Point(this.Location.X, this.Location.Y + 50);
this.Controls.Add(btnCheckExistDirectory);
btnCheckExistDirectory.Click += new EventHandler(btnCheckExistDirectory_Click);
}
void btnCheckExistFile_Click(object sender, EventArgs e)
{
// Kiểm tra sự tồn tại của tập tin
string filePath = @"D:/THS/Document/HRP/Recruity/Recruity.docx";
// @ đại diện cho chuỗi
if (System.IO.File.Exists(filePath))
MessageBox.Show("Tồn tại tập tin \"Recruity.docx\".");
else
MessageBox.Show("Không tồn tại Tập tin \"Recruity.docx\".");
}
void btnCheckExistDirectory_Click(object sender, EventArgs e)
{
// Kiểm tra sự tồn tại của thư mục
string dicrectoryPath = @"D:/THS/Document/HRP/Recruity";
// @ đại diện cho chuỗi
if (System.IO.Directory.Exists(dicrectoryPath))
MessageBox.Show("Tồn tại thư mục \"Recruity\".");
else
MessageBox.Show("Không tồn tại thư mục \"Recruity\".");
}
}
}
(theo gockinhnghiem.com)Chúc các bạn mai mắn!
Không có nhận xét nào:
Đăng nhận xét