了解 DirectoryInfo.Exists 上的布尔值

发布于 2024-08-25 09:52:50 字数 637 浏览 12 评论 0原文

var fileOpen = new OpenFileDialog(); var clickedOk = fileOpen.ShowDialog(); if (!((bool) clickedOk)) 返回;

var path = fileOpen.FileName;
var diPath = new DirectoryInfo(path);
var fiPath = new FileInfo(path);

Debug.WriteLine(diPath.Exists);

我只是想知道为什么 diPath.Exists 在这种情况下是假的?既然用户选择了文件,那么该目录就必须存在!?确实如此...

我已经使用 Directory.Exists(fiPath.DirectoryName) 进行了解决,但似乎很奇怪,上面的方法不起作用,并且需要其他 var 有点令人恼火检查我知道的东西是否存在,并且应该能够使用 diPath。这是怎么回事?

另外,关于一个相关问题,假设我有一个目录 C:\random\spot\here 的目录信息,为什么没有方法获取该字符串“C:\random\spot\here”,似乎我只能获取 Parent “spot” ”或名称“此处”。也许我错过了什么。

谢谢,

var fileOpen = new OpenFileDialog();
var clickedOk = fileOpen.ShowDialog();
if (!((bool) clickedOk)) return;

var path = fileOpen.FileName;
var diPath = new DirectoryInfo(path);
var fiPath = new FileInfo(path);

Debug.WriteLine(diPath.Exists);

I am just wondering why diPath.Exists is false in this case? Since the user has selected a file, the directory must exist!? and it does...

I have used a work around by using Directory.Exists(fiPath.DirectoryName) but it seems strange that the above isn't working, and slightly irritating to need that other var just to check something that I know is there exists, and should just be able to use the diPath. What's the deal?

Also on a related matter, say I have a directoryinfo for a directory C:\random\spot\here why is there no method to obtain that string "C:\random\spot\here" it seems I can only get Parent "spot" or Name "here". Maybe I missed something.

Thanks,

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

旧情勿念 2024-09-01 09:52:50

有一个名为path文件,但没有名为path的目录

var diPath = new DirectoryInfo(Path.GetDirectoryName(path));

可能就是你想要的。

There is a file called path but there is not directory called path.

var diPath = new DirectoryInfo(Path.GetDirectoryName(path));

is probably what you want.

爱要勇敢去追 2024-09-01 09:52:50

您在“路径”中包含文件名,因此路径将是叶节点(即文件)而不是目录(分支节点)。 Windows 文件/路径处理对于这类事情来说是非常字面的。

如前所述,如果使用路径,您可能需要使用 DirectoryInfo 或 Path.GetDirectoryName()。

Your including the filename in the "path", and as such the path will be a leaf node (i.e. file) and not a directory (branch node). Windows file/path handling is quite literal about those kind of things.

As mentioned previously DirectoryInfo or Path.GetDirectoryName() is probably what you want to use if working with paths.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文