C#目录不存在,但存在错误

问题描述 投票:1回答:3

正如标题所述,我有一个程序在继续之前检查目录是否存在。

并且当进行检查时,它说该目录不存在!

这是用于存储目录路径的代码:

string currentDirectory = Path.GetDirectoryName(Application.ExecutablePath);
Console.WriteLine("----" + currentDirectory.ToString());
string tesseractPath = Path.Combine(currentDirectory, @"..\..\..\tesseract");
_wrapper = new AsyncTesseractWrapper(tesseractPath);



public TesseractWrapper(string programLoc)
{
    DirectoryInfo dinfo = new DirectoryInfo(programLoc);
    //DirectoryInfo dinfo = new DirectoryInfo("C:\\Windows");
    ValidateTesseractDirectory(dinfo);
    _tesseractLocation = dinfo.FullName;
}

以及执行检查的代码:

private void ValidateTesseractDirectory(DirectoryInfo dinfo)
{
    if (!dinfo.Exists)               
        throw new ArgumentException("Specified program directory must exist.");
    FileInfo[] files;
    files = dinfo.GetFiles(_tessExe);
    if (files.Length != 1)
        throw new ArgumentException("Specified program directory must contain tesseract.exe.");
}

我尝试了几种变体进行调试,例如检查C:\ Windows文件夹是否存在,并且仍然给我一个错误...

代码是否有问题,或者我对.Exists方法的理解...?

谢谢!

c# file directory exists filesysteminfo
3个回答
3
投票

这可能是由于权限问题。引用MSDN:

Exists属性在尝试确定指定文件是否存在时如果发生任何错误,则返回false。在引发异常的情况下可能会发生这种情况,例如传递带有无效字符或太多字符的文件名,磁盘出现故障或丢失,或者调用者无权读取文件。


0
投票

[我认为问题在于,Microsoft已经更改了文件夹的结构,并且'显然'他们的员工仍在寻找'旧的好方法'。在过去的文件夹中曾经有“ ..”,这是“文件夹标记”(当然是dos),我可以看到它不再存在。我所做的:我将虚拟文件放入/复制到新文件夹,图像等中,而不是使用“目录”,而是使用file.exists我认为答案可能在于属性。


0
投票

实际经验相同。这是因为使用软链接(带有有关文件夹信息的文本文件)而不是联结。

首先递归加载文件夹,然后加载其文件并修复错误的连接。长文件名等。

public static List<string> GetFilesEveryFolder(string folder, string mask, SearchOption searchOption, bool _trimA1 = false)
{
    List<string> list = new List<string>(); ;
    List<string> dirs = null;

    try
    {
        dirs = GetFoldersEveryFolder(folder, "*").ToList();
    }
    catch (Exception ex)
    {
        throw new Exception("GetFiles with path: " + folder, ex);
    }

    foreach (var item in dirs)
    {
        try
        {
            list.AddRange(Directory.GetFiles(item, mask, SearchOption.TopDirectoryOnly));
        }
        catch (Exception ex)
        {
            // Not throw exception, it's probably Access denied on Documents and Settings etc
            //ThrowExceptions.FileSystemException(type, RH.CallingMethod(), ex);
        }
    }

    CA.ChangeContent(list, d => SH.FirstCharLower(d));

    if (_trimA1)
    {
        list = CA.ChangeContent(list, d => d = d.Replace(folder, ""));
    }
    return list;
}
© www.soinside.com 2019 - 2024. All rights reserved.