C#:在您拥有 DirectoryInfo 的目录中创建新的 FileInfo
我只是想知道您是否有例如:
var dir = new DirectoryInfo(@"C:\Temp");
是否有比这更简单/更清晰的方法来将新文件添加到该目录?
var file = new FileInfo(Path.Combine(dir.FullName, "file.ext"));
我想我可能可以制作一个扩展方法或其他东西,但很好奇是否已经存在一些在这里看不到的东西......我的意思是 DirectoryInfo
确实有 GetFiles()<例如 /code> 方法。
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"));
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你想做什么? 标题为“创建新文件”。 FileInfo 对象不是文件;而是文件。 它是一个保存有关文件信息的对象(可能存在也可能不存在)。 如果您确实想要创建该文件,有多种方法可以实现。 最简单的方法之一是:
如果您想基于
FileInfo
对象创建文件,则可以使用以下方法:作为旁注:它是
dir.FullName
,而不是dir.FullPath
。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:
If you want to create the file based on the
FileInfo
object instead, you can use the following approach:As a side note: it is
dir.FullName
, notdir.FullPath
.你为什么不使用:
或
Why don't you use:
or
虽然确实存在
Directorynfo.GetFiles()
方法,但它们仅返回磁盘上实际存在的文件。Path.Combine
是关于假设的路径。尝试这些扩展方法:
While there does exist
Directorynfo.GetFiles()
methods, they only return files that actually exist on disk.Path.Combine
is about hypothetical paths.Try these extension methods: