如果文件不存在,则创建文件

96

我需要让我的代码在文件不存在时创建文件,否则追加内容。目前的代码是:如果文件存在,则创建并追加内容。以下是代码:

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();
}

}


2
File.AppendAllText - 这一行代码完全满足您的需求。 - Shadow The Spring Wizard
@ShadowWizard 因为这被标记为作业,所以OP可能需要展示条件逻辑。 - Yuck
5
@Yuck - 重新发明轮子的作业?恶心!;) (翻译:你嘲笑这个作业要求我们重新发明轮子,觉得很无聊恶心。;)) - Shadow The Spring Wizard
9个回答

147
你可以简单地调用。
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>

21

或:

using FileStream fileStream = File.Open(path, FileMode.Append);
using StreamWriter file = new StreamWriter(fileStream);
// ...

3
对于这种情况,您会收到一个IOException,因为当StreamWriter想要写入文件时,fileStream仍然锁定该文件。相反,将fileStream作为参数传递给StreamWriter构造函数。 - salted

17

7

2021年

只需使用File.AppendAllText,它会在文件不存在时创建该文件:

File.AppendAllText("myFile.txt", "some text");

5

如果你想检查文件是否不存在,那么需要对File.Exists(path)取反。


3
在打开文件之前检查文件是否存在是一种错误的模式。这会引入竞态条件。请参阅其他答案以及我在另一个问题中的评论 - ComFreek

1
这将启用使用StreamWriter追加文件。
 using (StreamWriter stream = new StreamWriter("YourFilePath", true)) {...}

这是默认模式,不会追加到文件并创建一个新文件。
using (StreamWriter stream = new StreamWriter("YourFilePath", false)){...}
                           or
using (StreamWriter stream = new StreamWriter("YourFilePath")){...}

无论如何,如果您想检查文件是否存在并执行其他操作,可以使用:

using (StreamWriter sw = (File.Exists(path)) ? File.AppendText(path) : File.CreateText(path))
            {...}

1

这对我也有效。

string path = TextFile + ".txt";

if (!File.Exists(HttpContext.Current.Server.MapPath(path)))
{
    File.Create(HttpContext.Current.Server.MapPath(path)).Close();
}
using (StreamWriter w = File.AppendText(HttpContext.Current.Server.MapPath(path)))
{
    w.WriteLine("{0}", "Hello World");
    w.Flush();
    w.Close();
}

0
例如。
    string rootPath = Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.System));
        rootPath += "MTN";
        if (!(File.Exists(rootPath)))
        {
            File.CreateText(rootPath);
        }

检查文件是否存在再打开文件是一种错误的模式。这会引入竞态条件。请参阅其他答案和我在另一个问题上的评论 - ComFreek
我的模式类似于LINQ中的包含。我的意思是这很正常。有时候文件需要授权,打开文件应该是我们的第二个解决方案,而不是答案。 - Metin Atalay
@MetinAtalay,非常抱歉,我没有完全理解您的评论。我的担忧是,如果文件在if (!(File.Exists(...)))之后但在File.CreateText(...)之前被外部创建,则会被覆盖。 - ComFreek

0
private List<Url> AddURLToFile(Urls urls, Url url)
{
    string filePath = @"D:\test\file.json";
    urls.UrlList.Add(url);

    //if (!System.IO.File.Exists(filePath))
    //    using (System.IO.File.Delete(filePath));

    System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(urls.UrlList));

    //using (StreamWriter sw = (System.IO.File.Exists(filePath)) ? System.IO.File.AppendText(filePath) : System.IO.File.CreateText(filePath))
    //{
    //    sw.WriteLine(JsonConvert.SerializeObject(urls.UrlList));
    //}
    return urls.UrlList;
}

private List<Url> ReadURLToFile()
{
    //  string filePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"App_Data\file.json");
    string filePath = @"D:\test\file.json";

    List<Url> result = new List<Url>(); ;
    if (!System.IO.File.Exists(filePath))
        using (System.IO.File.CreateText(filePath)) ;



    using (StreamReader file = new StreamReader(filePath))
    {
        result = JsonConvert.DeserializeObject<List<Url>>(file.ReadToEnd());
        file.Close();
    }
    if (result == null)
        result = new List<Url>();

    return result;

}

欢迎来到SO。请提供更多信息,说明为什么这段代码可以回答问题。此外,请提供一个[mcve]。 - Mathias

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接