简体   繁体   English

C#中带有非ASCII字符和FileInfo的文件路径

[英]File paths with non-ascii characters and FileInfo in C#

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: 我用它制作了FileInfo,但是当我检查它的存在时,它返回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. 在调试时,确保blah存在且内部有斑点,然后file.Exists开始返回true。 So I believe the problem is the non-ascii character. 因此,我认为问题在于非ASCII字符。

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. 一部分来自应用程序的AppDomain,它是包含“á”的部分,另一部分以某种方式来自用户。 Both parts are put together by Path.Combine. 这两部分由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? 我应该如何处理一个字符串,以便即使它包含非ASCII字符,它也仍然是有效路径?

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. 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;
}

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. 注意:Exists方法不应用于路径验证,该方法仅检查path中指定的文件是否存在。 Passing an invalid path to Exists returns false. 将无效路径传递给Exists将返回false。

For path validation you can use Directory.Exists. 对于路径验证,可以使用Directory.Exists。

I have just manuall created a bláh folder containing a bleh file, and with that in place, this code prints True as expected: 我刚刚手动创建了一个包含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();
        }
    }
}

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. 我建议您检查字符串的来源-特别是,尽管您的3k代表说这是问题所在,但请记住,将反斜杠表示为\\\\是C#语法的产物,并且您要确保字符串实际上仅包含单\\秒。

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. 参考@adatapost的回复,无效文件名字符的列表(从System.IO.Path.GetInvalidFileNameChars()中收集到System.IO.Path.GetInvalidFileNameChars()实际上不包含带有变音符号的常规字符。

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 . 在这种情况下,您需要尝试打开一个具有相同名称而不是 c:\\bloh\\bleh

Look like the "bleh" in the path is a directory, not a file. 看起来路径中的“ bleh”是目录,而不是文件。 To check if the folder exist use Directory.Exists method. 要检查文件夹是否存在,请使用Directory.Exists方法。

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. 看来,当我不进行实验时,以某种方式设法重现了权限问题,可能是通过手工创建了没有非ascii字符的文件夹并复制了另一个文件夹。

Oh... so embarrassing. 哦,好尴尬。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM