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

时间:2012-04-30 11:37:51

标签: c# streamwriter

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

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

}

8 个答案:

答案 0 :(得分:90)

您只需致电

即可
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>

答案 1 :(得分:15)

或:

using(var fileStream = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
    using (StreamWriter sw = new StreamWriter(path, true))
    {
        //...
    }
}

答案 2 :(得分:12)

您甚至不需要手动进行检查,File.Open会为您完成检查。尝试:

using (StreamWriter sw = new StreamWriter(File.Open(path, System.IO.FileMode.Append))) 
{

参考:http://msdn.microsoft.com/en-us/library/system.io.filemode.aspx

答案 3 :(得分:7)

是的,如果要检查文件是否,则需要否定File.Exists(path)

答案 4 :(得分:1)

例如

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

答案 5 :(得分: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;

}

答案 6 :(得分:0)

这对我也很好

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

答案 7 :(得分:0)

这将允许使用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))
            {...}