我需要让我的代码读取文件是否存在创建else附加.现在它正在读取它是否确实存在创建和追加.这是代码:
if (File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
Run Code Online (Sandbox Code Playgroud)
我会这样做吗?
if (! File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
Run Code Online (Sandbox Code Playgroud)
编辑:
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();
}
Run Code Online (Sandbox Code Playgroud)
}
我正在写一个文本文件,每次我写,我想清除文本文件.
try
{
string fileName = "Profile//" + comboboxSelectProfile.SelectedItem.ToString() + ".txt";
using (StreamWriter sw = new StreamWriter(("Default//DefaultProfile.txt").ToString(), true))
{
sw.WriteLine(fileName);
MessageBox.Show("Default is set!");
}
DefaultFileName = "Default//DefaultProfile.txt";
}
catch
{
}
Run Code Online (Sandbox Code Playgroud)
我该怎么做呢?我想从DefaultProfile.txt中删除所有以前的内容.
我实际上必须知道从文本文件中删除所有内容的方法或方法(只是一个名称).