代码之家  ›  专栏  ›  技术社区  ›  Diskdrive

如果目录不存在,如何创建文件?

  •  170
  • Diskdrive  · 技术社区  · 14 年前

    如果目录不存在,我这里有一段代码会中断:

    System.IO.File.WriteAllText(filePath, content);
    

    在一行(或几行)中,是否可以检查指向新文件的目录是否不存在,如果不存在,是否可以在创建新文件之前创建它?

    我用的是.NET 3.5。

    5 回复  |  直到 6 年前
        1
  •  339
  •   BenKoshy Mayinx    6 年前

    创造

    (new FileInfo(filePath)).Directory.Create() 在写入文件之前。

    ….或者,如果存在,则创建(否则不执行任何操作)

    System.IO.FileInfo file = new System.IO.FileInfo(filePath);
    file.Directory.Create(); // If the directory already exists, this method does nothing.
    System.IO.File.WriteAllText(file.FullName, content);
    
        2
  •  99
  •   Ram    9 年前

    您可以使用以下代码

      DirectoryInfo di = Directory.CreateDirectory(path);
    
        3
  •  28
  •   SwDevMan81    13 年前

    正如@hitec所说,您必须确保您拥有正确的权限,如果这样做,您可以使用此行来确保目录的存在:

    Directory.CreateDirectory(Path.GetDirectoryName(filePath))

        4
  •  -1
  •   Peter Mortensen Len Greski    9 年前

    你可以使用 File.Exists 检查文件是否存在并使用 File.Create 如果需要的话。确保检查您是否有权在该位置创建文件。

    一旦确定该文件存在,就可以安全地写入该文件。尽管作为一种预防措施,您应该将代码放入一个try…catch块中,并捕获如果事情不按计划进行,函数可能引发的异常。

    Additional information for basic file I/O concepts .

        5
  •  -2
  •   Godwin Awojobi    9 年前

    var filePath = context.Server.MapPath(Convert.ToString(ConfigurationManager.AppSettings["ErrorLogFile"]));

    var file = new FileInfo(filePath);

    file.Directory.Create(); 如果目录已经存在,则此方法不执行任何操作。

    var sw = new StreamWriter(filePath, true);

    sw.WriteLine(Enter your message here);

    sw.Close();