相关疑难解决方法(0)

检查.NET中的目录和文件写入权限

在我的.NET 2.0应用程序中,我需要检查是否有足够的权限来创建和写入目录的文件.为此,我有以下函数尝试创建一个文件并向其写入一个字节,然后删除自己以测试权限是否存在.

我认为检查的最佳方法是实际尝试并执行此操作,捕获发生的任何异常.虽然我对一般的异常捕获并不是特别高兴,所以有更好的或者更可接受的方式吗?

private const string TEMP_FILE = "\\tempFile.tmp";

/// <summary>
/// Checks the ability to create and write to a file in the supplied directory.
/// </summary>
/// <param name="directory">String representing the directory path to check.</param>
/// <returns>True if successful; otherwise false.</returns>
private static bool CheckDirectoryAccess(string directory)
{
    bool success = false;
    string fullPath = directory + TEMP_FILE;

    if (Directory.Exists(directory))
    {
        try
        {
            using (FileStream fs = new FileStream(fullPath, FileMode.CreateNew, 
                                                            FileAccess.Write))
            {
                fs.WriteByte(0xff);
            }

            if (File.Exists(fullPath))
            {
                File.Delete(fullPath);
                success …
Run Code Online (Sandbox Code Playgroud)

.net c# directory file-permissions winforms

75
推荐指数
5
解决办法
11万
查看次数

什么时候可以检查文件是否存在?

文件系统是不稳定的.这意味着您不能相信一个操作的结果仍然对下一个操作有效,即使它是下一行代码.你不能只说if (some file exists and I have permissions for it) open the file,你不能说if (some file does not exist) create the file.您的if条件结果总是可能会在代码的两个部分之间发生变化.操作是截然不同的:不是原子的.

更糟糕的是,问题的本质意味着如果你想要进行这种检查,你可能已经担心或意识到你无法控制的东西很可能发生在文件上.开发环境的本质使得此事件在测试期间不太可能发生,并且很难再现.因此,您不仅会遇到错误,而且在测试时也不会显示错误.

因此,在正常情况下,最好的做法是甚至不尝试检查文件或目录是否存在.相反,将您的开发时间用于处理文件系统中的异常.无论如何,您必须处理这些异常,这样可以更好地利用您的资源.即使异常很慢,检查文件是否需要额外的磁盘访问,磁盘访问速度慢得多.在另一个问题中,我甚至对这个效果有一个很好的答案.

但我有些疑惑.例如,在.Net中,如果确实总是如此,那么这些.Exists()方法首先不会出现在API中.还要考虑您希望程序需要创建文件的方案.想到的第一个例子是桌面应用程序.此应用程序将默认用户配置文件安装到其主目录,并且每个用户第一次启动应用程序时,它会将此文件复制到该用户的应用程序数据文件夹.它希望该文件在第一次启动时不存在.

那么什么时候可以提前检查文件的存在(或其他属性,如大小和权限)?是否期望在第一次尝试时失败而不是成功足够的经验法则?

language-agnostic filesystems

35
推荐指数
3
解决办法
3579
查看次数

使用c#确定文件是否存在并解析UNC路径

我正在尝试编写一个函数来确定文件是否存在.这两种方法证明返回不一致的结果(fileExists()似乎提供了准确的结果,与isFileFound()相比,它返回​​误报 - 我试图创建实例时会发生异常).

protected bool isFileFound(string path, string fileName)
    {
        System.IO.FileInfo fi = null;

        bool found = false;
        try
        {
            fi = new System.IO.FileInfo(path + fileName);
            found = true;
        }
        catch (Exception e)
        {
            baselogger.Fatal(e.Message + " " + e.StackTrace + " \n" + path + fileName);
        }

        return found;
    }

    protected bool fileExists(string path, string pattern)
    {
        bool success = false;

        try
        {
            success = File.Exists(path + pattern);
        }
        catch (Exception e)
        {
            baselogger.Warn(e.Message + " " + e.StackTrace …
Run Code Online (Sandbox Code Playgroud)

c# filesystems

29
推荐指数
2
解决办法
6万
查看次数

检查FTP服务器上是否存在目录

我正在检查我的FTP服务器上是否存在目录:

    public bool DirectoryExists(string directory)
    {
        bool directoryExists;

        var request = (FtpWebRequest)WebRequest.Create(directory);
        request.Method = WebRequestMethods.Ftp.ListDirectory;
        request.Credentials = new NetworkCredential("user", "pass");

        try
        {
            using (request.GetResponse())
            {
                directoryExists = true;
            }
        }
        catch (WebException)
        {
            directoryExists = false;
        }

        return directoryExists;
    }
Run Code Online (Sandbox Code Playgroud)

在这种情况下:

directory = @"ftp://ftp.example.com/Rubicon";
Run Code Online (Sandbox Code Playgroud)

在我的服务器上,我有一个名为的文件夹Rubicon1.这导致我的支票返回true.除非它与目录名称完全匹配,否则如何确保它失败?

c# ftp ftpwebrequest

10
推荐指数
1
解决办法
1万
查看次数

检查是否可以读取文件

这就是我试图检查是否可以在实际读取之前读取文件的方法

FileStream stream = new FileStream();
try
{
   // try to open the file to check if we can access it for read
   stream = File.Open(this.DataSourceFileName, FileMode.Open, FileAccess.Read);
}
catch (IOException ex)
{
   return false;
}
finally
{
   stream.Dispose();
}
Run Code Online (Sandbox Code Playgroud)

这是正确的方法吗?

File.Open类似于File.ReadAllText,我的意思是,它们的性能同样昂贵吗?

c# io file-io

10
推荐指数
2
解决办法
2万
查看次数

检查文件/文件夹访问权限

我得到一个UnautorizedAccessException运行此代码:

string[] fileList = Directory.GetFiles(strDir, strExt);
Run Code Online (Sandbox Code Playgroud)

发生在异常c:\users\username\appdata 如何,我可以检查我是否有访问权限(列出和读取文件)?

.net c# vb.net file-permissions

9
推荐指数
1
解决办法
4万
查看次数

在.NET中,检查当前用户是否可以写入目录

在.NET中,有一种简单的方法可以检查当前用户是否有权在目录中创建文件?相当于C++ _access函数的东西是理想的.

我不想使用反复试验(创建一个虚拟文件然后删除它):除了看似hackish之外,其他软件正在监视有问题的目录以查找丢弃的文件.

我不想使用System.DirectoryServices:查看ACL,解析组成员身份以及来自不同组成员身份的权限如何交互似乎容易出错且太难.某处肯定有一个好的或不可能的功能,不是吗?

提前致谢!

[编辑]作为奖励,如果它也适用于网络共享,那就太酷了.

.net permissions

8
推荐指数
2
解决办法
1万
查看次数

trycatch如何伤害内存/ CPU?

所以我对它的c#侧感兴趣 - 但我正在标记c ++,因为这里存在概念而我并没有超过'finally'关键字.所以无论如何 - 在线是否存在关于try-catch如何减速或将使用更多内存而不是简单的'if-else'或其他代码的基准测试?例如,现在我正在编写代码并使用Streamwriter,当您将鼠标悬停在它上面时会显示7个可能的异常...所以如果我写下这样的话会有人声称它会更快:

//////////////
if(path is not too long)
{ if(file exists)
{ if(nothing else uses the file)
{ if(user is authorized)
}}}
////////////
Run Code Online (Sandbox Code Playgroud)

你有7个条件,你可以使用try-catch - 更不用说这些条件不能简化为单个if语句.

10倍!

c# exception-handling

4
推荐指数
1
解决办法
1249
查看次数

VB.Net中的文件比较

我需要知道两个文件是否相同.起初我比较了文件大小和创建时间戳,但这不够可靠.我已经提出了以下代码,这似乎有效,但我希望有人能够更好,更容易或更快地完成这项工作.

基本上我正在做的是将文件内容流式传输到字节数组,并通过System.Security.Cryptography比较它们的MD5哈希值.

在此之前,我做了一些简单的检查,因为没有理由读取文件,如果两个文件路径相同,或者其中一个文件不存在.

Public Function CompareFiles(ByVal file1FullPath As String, ByVal file2FullPath As String) As Boolean

    If Not File.Exists(file1FullPath) Or Not File.Exists(file2FullPath) Then
        'One or both of the files does not exist.
        Return False
    End If

    If String.Compare(file1FullPath, file2FullPath, True) = 0 Then
        ' fileFullPath1 and fileFullPath2 points to the same file...
        Return True
    End If

    Dim MD5Crypto As New MD5CryptoServiceProvider()
    Dim textEncoding As New System.Text.ASCIIEncoding()

    Dim fileBytes1() As Byte, fileBytes2() As Byte
    Dim fileContents1, fileContents2 As String
    Dim streamReader As …
Run Code Online (Sandbox Code Playgroud)

vb.net comparison filestream

4
推荐指数
1
解决办法
3866
查看次数

如何检查是否拒绝访问字符串路径?

我想知道如何测试我是否可以访问字符串路径.这是我使用的代码:

using System;
using System.IO;

namescpace prog1
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"C:\Users\Admin";
            DirectoryInfo dir = new DirectoryInfo(path);
            foreach (FileInfo fil in dir.GetFiles())
            {
                //At dir.GetFiles, I get an error  saying
                //access to the string path is denied.

                Console.WriteLine(fil.Name);
            }
            Console.ReadLine();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我想测试访问是否被拒绝(到字符串路径)然后执行GetFiles和所有这些.

我已经发现了这个问题:如何轻松检查.NET中的文件是否被拒绝访问?

有帮助吗?

c# file-access

1
推荐指数
1
解决办法
3694
查看次数