且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#:在具有DirectoryInfo的目录中创建一个新的FileInfo

更新时间:2023-11-30 14:16:52

你想做什么?标题说创建新文件。 FileInfo对象不是文件;它是一个保存有关文件的信息的对象(可能存在或可能不存在)。如果你真的想要创建文件,那么有很多方法可以这样做。最简单的方法之一是:

What is it that you want to do? The title says "Creating a new file". A FileInfo object is not a file; it's an object holding information about a file (that may or may not exist). If you actually want to create the file, there are a number of ways of doing so. One of the simplest ways would be this:

File.WriteAllText(Path.Combine(dir.FullName, "file.ext"), "some text");

如果要根据 FileInfo $ c创建文件$ c> object,可以使用以下方法:

If you want to create the file based on the FileInfo object instead, you can use the following approach:

var dir = new DirectoryInfo(@"C:\Temp");
var file = new FileInfo(Path.Combine(dir.FullName, "file.ext"));
if (!file.Exists) // you may not want to overwrite existing files
{
    using (Stream stream = file.OpenWrite())
    using (StreamWriter writer = new StreamWriter(stream))
    {
        writer.Write("some text");
    }
}

作为附注:它是 dir.FullName ,而不是 dir.FullPath

As a side note: it is dir.FullName, not dir.FullPath.