Tôi cần lấy mã của mình để đọc nếu tệp không tồn tại tạo khác thêm. Ngay bây giờ nó đang đọc nếu nó tồn tại tạo và nối thêm. Đây là mã:Tạo tệp nếu tệp không tồn tại
if (File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
Tôi có làm điều này không?
if (! File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
Edit:
string path = txtFilePath.Text;
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
foreach (var line in employeeList.Items)
{
sw.WriteLine(((Employee)line).FirstName);
sw.WriteLine(((Employee)line).LastName);
sw.WriteLine(((Employee)line).JobTitle);
}
}
}
else
{
StreamWriter sw = File.AppendText(path);
foreach (var line in employeeList.Items)
{
sw.WriteLine(((Employee)line).FirstName);
sw.WriteLine(((Employee)line).LastName);
sw.WriteLine(((Employee)line).JobTitle);
}
sw.Close();
}
}
[File.AppendAllText] (http: // MSDN .microsoft.com/en-us/library/ms143356.aspx) - điều này đang làm chính xác những gì bạn cần trong một dòng mã. –
@ShadowWizard Kể từ lần thứ được gắn thẻ bài tập về nhà OP thực sự có thể được hướng dẫn để hiển thị logic có điều kiện. – Yuck
@Yuck - bài tập về nhà để phát minh lại bánh xe? Kinh quá! ;) –