C# 中包含非 ascii 字符的文件路径和 FileInfo

发布于 2024-08-02 10:31:08 字数 584 浏览 5 评论 0原文

我得到一个或多或少看起来像这样的字符串:

"C:\\bláh\\bleh"

我用它创建了一个 FileInfo,但是当我检查它是否存在时,它返回 false:

var file = new FileInfo(path);
file.Exists;

如果我在调试时手动重命名路径

"C:\\blah\\bleh"

并确保 blah 存在且其中有 bleh ,然后 file.Exists 开始返回 true。所以我认为问题出在非 ASCII 字符上。

实际的字符串是由我的程序构建的。一部分来自应用程序的 AppDomain,即包含“á”的部分,另一部分在某种程度上来自用户。两个部分通过 Path.Combine 组合在一起。我通过两种方式确认了结果字符串的有效性:将其从我的程序生成的错误(其中包括路径)复制到资源管理器中,可以很好地打开文件。在调试器中查看该字符串,它看起来正确转义,因为 \ 被写为 \。 “á”由调试器按文字打印。

我应该如何处理字符串,以便即使它具有非 ASCII 字符,它也能成为有效路径?

I get a string that more or less looks like this:

"C:\\bláh\\bleh"

I make a FileInfo with it, but when I check for its existence it returns false:

var file = new FileInfo(path);
file.Exists;

If I manually rename the path to

"C:\\blah\\bleh"

at debug time and ensure that blah exists with a bleh inside it, then file.Exists starts returning true. So I believe the problem is the non-ascii character.

The actual string is built by my program. One part comes from the AppDomain of the application, which is the part that contains the "á", the other part comes, in a way, from the user. Both parts are put together by Path.Combine. I confirmed the validity of the resulting string in two ways: copying it from the error my program generates, which includes the path, into explorer opens the file just fine. Looking at that string at the debugger, it looks correctly escaped, in that \ are written as \. The "á" is printed literarily by the debugger.

How should I process a string so that even if it has non-ascii characters it turns out to be a valid path?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

东京女 2024-08-09 10:31:09

问题是:程序没有足够的权限来访问该文件。修复权限解决了问题。看来,当我没有进行实验时,我以某种方式设法重现了权限问题,可能是通过手动创建没有非 ASCII 字符的文件夹并复制另一个文件夹。

哦……好尴尬啊。

The problem was: the program didn't have enough permissions to access that file. Fixing the permissions fixed the problem. It seems that when I didn't my experiment I somehow managed to reproduce the permission problem, possibly by creating the folder without the non-ascii character by hand and copying the other one.

Oh... so embarrassing.

£冰雨忧蓝° 2024-08-09 10:31:08

这是一种处理文件名中的变音符号的方法。 File.Exists 方法的成功取决于系统存储文件名的方式。

public bool FileExists(string sPath)
{
  //Checking for composed and decomposed is to handle diacritics in filenames.  
  var pathComposed = sPath.Normalize(NormalizationForm.FormC);
  if (File.Exists(pathComposed))    
      return true;

   //We really need to check both possibilities.
   var pathDecomposed = sPath.Normalize(NormalizationForm.FormD);
   if (File.Exists(pathDecomposed))     
      return true;

   return false;
}

Here is a method that will handle diacritics in filenames. The success of the File.Exists method depends on how your system stores the filename.

public bool FileExists(string sPath)
{
  //Checking for composed and decomposed is to handle diacritics in filenames.  
  var pathComposed = sPath.Normalize(NormalizationForm.FormC);
  if (File.Exists(pathComposed))    
      return true;

   //We really need to check both possibilities.
   var pathDecomposed = sPath.Normalize(NormalizationForm.FormD);
   if (File.Exists(pathDecomposed))     
      return true;

   return false;
}
请你别敷衍 2024-08-09 10:31:08

试试这个

    string sourceFile = @"C:\bláh\bleh";
    if (File.Exists(sourceFile))
    {

         Console.WriteLine("file exist.");

    }
    else
    {
        Console.WriteLine("file does not exist.");

    }

注意:Exists 方法不应用于路径验证,此方法仅检查路径中指定的文件是否存在。将无效路径传递给 Exists 将返回 false。

对于路径验证,您可以使用 Directory.Exists。

try this

    string sourceFile = @"C:\bláh\bleh";
    if (File.Exists(sourceFile))
    {

         Console.WriteLine("file exist.");

    }
    else
    {
        Console.WriteLine("file does not exist.");

    }

Note : The Exists method should not be used for path validation, this method merely checks if the file specified in path exists. Passing an invalid path to Exists returns false.

For path validation you can use Directory.Exists.

网白 2024-08-09 10:31:08

我刚刚手动创建了一个包含 bleh 文件的 bláh 文件夹,并且就位后,此代码按预期打印 True

using System;
using System.IO;

namespace ConsoleApplication72
{
    class Program
    {
        static void Main(string[] args)
        {
            string filename = "c:\\bláh\\bleh";

            FileInfo fi = new FileInfo(filename);

            Console.WriteLine(fi.Exists);

            Console.ReadLine();
        }
    }
}

我建议检查您的字符串的来源 - 特别是,尽管您的 3k 代表反对这就是问题,请记住,将反斜杠表示为 \\ 是 C# 语法的产物,并且您要确保字符串实际上只包含单个 \

I have just manuall created a bláh folder containing a bleh file, and with that in place, this code prints True as expected:

using System;
using System.IO;

namespace ConsoleApplication72
{
    class Program
    {
        static void Main(string[] args)
        {
            string filename = "c:\\bláh\\bleh";

            FileInfo fi = new FileInfo(filename);

            Console.WriteLine(fi.Exists);

            Console.ReadLine();
        }
    }
}

I would suggest checking the source of your string - in particular, although your 3k rep speaks against this being the problem, remember that expressing a backslash as \\ is an artifact of C# syntax, and you want to make sure your string actually contains only single \s.

看透却不说透 2024-08-09 10:31:08

参考@adatapost的回复,无效文件名字符列表(从System.IO.Path.GetInvalidFileNameChars()收集)实际上不包含带变音符号的正常字符。

它看起来像你的问题我真正要问的是,“如何删除字符串中的变音符号(或者在本例中为文件路径)?”。

或者您可能没有问这个问题,并且您确实想找到一个名为:(

c:\blòh\bleh

或类似名称)的文件。在这种情况下,然后您需要尝试打开同名的文件,而不能c:\bloh\bleh

Referring to @adatapost's reply, the list of invalid file name characters (gleaned from System.IO.Path.GetInvalidFileNameChars() in fact doesn't contain normal characters with diacritics.

It looks like the question you're really asking is, "How do I remove diacritics from a string (or in this case, file path)?".

Or maybe you aren't asking this question, and you genuinely want to find a file with name:

c:\blòh\bleh

(or something similar). In that case, you then need to try to open a file with the same name, and not c:\bloh\bleh.

晨敛清荷 2024-08-09 10:31:08

看起来路径中的“bleh”是一个目录,而不是文件。要检查文件夹是否存在,请使用 Directory.Exists 方法。

Look like the "bleh" in the path is a directory, not a file. To check if the folder exist use Directory.Exists method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文