C#:在具有DirectoryInfo的目录中创建一个新的FileInfo [英] C#: Creating a new FileInfo in a directory that you have the DirectoryInfo of

查看:98
本文介绍了C#:在具有DirectoryInfo的目录中创建一个新的FileInfo的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道你有什么例子:

I was just wondering when you have for example:

var dir = new DirectoryInfo(@"C:\Temp");

有没有比这更容易/更清晰的方式添加到该目录的新文件?

Is there an easier/clearer way to add a new file to that directory than this?

var file = new FileInfo(Path.Combine(dir.FullName, "file.ext"));

我想我可能只是做一个扩展方法或东西,但好奇,如果已经存在这不能看到这里...我的意思是 DirectoryInfo GetFiles()方法,例如。 p>

I'm thinking I can probably just make an extension method or something, but curious if something already exists that can't see here... I mean the DirectoryInfo does have GetFiles() method for example.

推荐答案

你想做什么?标题说创建新文件。 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 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.

这篇关于C#:在具有DirectoryInfo的目录中创建一个新的FileInfo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆