如何检查,如果我能在一个特定的文件夹中创建一个文件 [英] How to check if I can create a file in a specific folder

查看:118
本文介绍了如何检查,如果我能在一个特定的文件夹中创建一个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道,如果我可以创建一个特定的文件夹中的文件,但也有太多的事情要检查,如权限,重复的文件,等等。 我在寻找类似 File.CanCreate(@C:\ MyFolder的\ myfile.aaa),但还没有找到这样的方法。 我认为唯一的办法是尝试创建一个虚拟文件,并检查是否有异常,但是这是一个ungly的解决方案,也会影响性能。 你知道一个更好的解决方案?

I need to know if I can create a file in a specific folder, but there are too many things to check such as permissions, duplicate files, etc. I'm looking for something like File.CanCreate(@"C:\myfolder\myfile.aaa"), but haven't found such a method. The only thing I thought is to try to create a dummy file and check for exceptions but this is an ungly solution that also affects performance. Do you know a better solution?

推荐答案

在现实中,创建一个虚拟的文件是不会在大多数应用中一个巨大的性能影响。当然,如果你有创建高级权限,但没有摧毁它可能会有点毛毛......

In reality, creating a dummy file isn't going to have a huge performance impact in most applications. Of course, if you have advanced permissions with create but not destroy it might get a bit hairy...

GUID是常常对随机的名字(避免冲突) - 是这样的:

Guids are always handy for random names (to avoid conflicts) - something like:

string file = Path.Combine(dir, Guid.NewGuid().ToString() + ".tmp");
// perhaps check File.Exists(file), but it would be a long-shot...
bool canCreate;
try
{
    using (File.Create(file)) { }
    File.Delete(file);
    canCreate = true;
}
catch
{
    canCreate = false;
}

这篇关于如何检查,如果我能在一个特定的文件夹中创建一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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