在忽略路径和文件名中的大小写的同时打开文件

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

我可以将pathAndFilename转换为小写,但它就像我需要一种方法来告诉OpenRead不区分大小写。

// pathAndFileName has been converted with .ToLower()
using (FileStream fileStream = File.OpenRead(pathAndFileName))
{
    Bitmap bitmap = new Bitmap(fileStream);
    Image image = (Image)bitmap;
}
c# .net case-insensitive
1个回答
2
投票

如果您尝试访问运行Linux的计算机或文件名区分大小写的其他操作系统上的文件,则可以(未经测试!)使用您拥有的文件名作为模式列出目录中的文件。请注意,可能存在多个具有相同名称和不同拼写变体的文件。在这种情况下,此辅助函数将引发异常。

static void Main(string[] args)
{
    string pathAndFileName = ..your file name...;
    string resultFileName = GetActualCaseForFileName(pathAndFileName);

    using (FileStream fileStream = File.OpenRead(resultFileName))
    {
        Bitmap bitmap = new Bitmap(fileStream);
        Image image = (Image)bitmap;
    }    


    Console.WriteLine(resultFileName);
}

private static string GetActualCaseForFileName(string pathAndFileName)
{
    string directory = Path.GetDirectoryName(pathAndFileName);
    string pattern = Path.GetFileName(pathAndFileName);
    string resultFileName;

    // Enumerate all files in the directory, using the file name as a pattern
    // This will list all case variants of the filename even on file systems that
    // are case sensitive
    IEnumerable<string> foundFiles = Directory.EnumerateFiles(directory, pattern);

    if (foundFiles.Any())
    {
        if (foundFiles.Count() > 1)
        {
            // More than two files with the same name but different case spelling found
            throw new Exception("Ambiguous File reference for " + pathAndFileName);
        }
        else
        {
            resultFileName = foundFiles.First();
        }
    }
    else
    {
        throw new FileNotFoundException("File not found" + pathAndFileName, pathAndFileName);
    }

    return resultFileName;
}
© www.soinside.com 2019 - 2024. All rights reserved.