如果文件不存在,我需要让我的代码读取,否则创建追加。现在它正在读取它是否确实存在创建和追加。这是代码:
if (File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
我会这样做吗?
if (! File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
编辑:
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();
}
最佳答案
你可以简单地调用
using (StreamWriter w = File.AppendText("log.txt"))
如果文件不存在,它将创建文件并打开文件进行追加。
编辑:
这就足够了:
string path = txtFilePath.Text;
using(StreamWriter sw = File.AppendText(path))
{
foreach (var line in employeeList.Items)
{
Employee e = (Employee)line; // unbox once
sw.WriteLine(e.FirstName);
sw.WriteLine(e.LastName);
sw.WriteLine(e.JobTitle);
}
}
但如果你坚持先检查,你可以这样做,但我不明白这一点。
string path = txtFilePath.Text;
using (StreamWriter sw = (File.Exists(path)) ? File.AppendText(path) : File.CreateText(path))
{
foreach (var line in employeeList.Items)
{
sw.WriteLine(((Employee)line).FirstName);
sw.WriteLine(((Employee)line).LastName);
sw.WriteLine(((Employee)line).JobTitle);
}
}
此外,要指出您的代码的一件事是您进行了很多不必要的拆箱操作。如果您必须使用像 ArrayList
这样的普通(非通用)集合,然后将对象拆箱一次并使用引用。
不过,我更喜欢使用 List<>
对于我的收藏:
public class EmployeeList : List<Employee>
关于c# - 如果文件不存在则创建文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10383053/