c# - 如果文件不存在则创建文件

标签 c# streamwriter

如果文件不存在,我需要让我的代码读取,否则创建追加。现在它正在读取它是否确实存在创建和追加。这是代码:

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/

相关文章:

c# - C+ +'s equivalent to C#' s 字典和列表

Powershell - Streamwriter

c# - 使用StreamReader/StreamWriter抓取日志导致程序停止响应

c# - Streamwriter 有时会在一行中间切断我的最后几行?

c# - 如何禁用控制台窗口上下文菜单的 `Close` 项?

C# IsGenericType 没有按预期工作

c# - 如何将此 LINQ 查询转换为延迟加载

C# 双格式对齐小数点

c# - 如何定期将 c# FileStream 刷新到磁盘?

c# - 将SQL信息写入TXT文件