如何验证在C#中访问文件 [英] how to validate Access a file in C#

查看:142
本文介绍了如何验证在C#中访问文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Winforms,C#,VS中的应用程序,此应用程序必须将pdf保存在所选的文件夹中,但首先我在启动应用程序时验证,如果它可以访问此文件夹,否则无法启动应用程序并显示警告。



如何验证我的应用程序是否具有对文件夹的写入权限。



关于

I'm working on an application in Winforms, C #, VS, this application has to save a pdf in a folder selected, but first I validate when starting the app, If it can access this folder, otherwise not start the app and shows warning.

How can I validate my app has write access to a folder.

regards

推荐答案

正如SA所说,只是尝试创建文件。下面是一个简单的例程,如果可以在指定的目录中创建文件,则返回true。

As SA said, just try to create the file. Below is a simple routine that returns true if a file can be created in the specified directory.
private bool CheckDirectoryWriteAccess(string dirPath)
{
    bool result = false;
    // check for directory access
    if (System.IO.Directory.Exists(dirPath))
    {
        try
        {
            // initalize temp filenam
            string filename = System.DateTime.Now.ToString("yyyymmdd_hhmmss_fff") + ".tmp";
            // try to create temp file
            System.IO.File.Create(dirPath + filename).Close();
            // check file exists and set return result
            if (System.IO.File.Exists(dirPath + filename))
            {
                result = true;
            }
            // delete temp file
            System.IO.File.Delete(dirPath + filename);                    
        }
        catch (UnauthorizedAccessException ex)
        {
            // code to handle UnauthorizedAccessException
        }
        catch (Exception ex)
        {
            // code to handle all other exceptions
        }

    }
    return result;
}


这些天很多学生都被教授防御性编程:在做某事之前,检查一下你是否能做到。在许多情况下,应该这样做,并且在许多其他情况下,这是非常错误的,过时的和低效的方法。通常,编程应该冒犯:只是做操作,不要问你是否可以。你总是可以在try-catch下执行代码(通常你应该这样做),让异常传播并最终处理它。如果由于访问冲突而被抛出异常并被捕获,则您没有超出部分。这不是那么简单吗?



所以,我建议采用简单实用的方法:不要做防御性编程,做些冒犯。如果未抛出权限被拒绝的异常,则用户具有访问权限,并且操作已完成。如果它被抛出 - 告知用户失败及其原因。


就这么简单。



-SA
Many students these days are taught defensive programming: before doing something, check up if you can do it. In many cases, this should be done, and, in many other cases, this is quite wrong, obsolete and inefficient approach. Very often, programming should be offensive: just do the operation, don't ask if you can. You can always execute code under try-catch (and most usually you should), let the exception propagate and eventually handle it. If exception was thrown due to access violation and caught, you don't have the excess. Isn't that simple?

So, I'm suggesting the simple and practical approach: don't do defensive programming, do offensive. If the permission denied exception is not thrown, the user has the access, and the operation is already done. If it was thrown — inform the user of the failure and its reason.

As simple as that.

—SA


这篇关于如何验证在C#中访问文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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