C# ReadAllText 文件不存在

Sir*_*aul 3 c# file visual-studio

我正在创建一个非常基本的程序来尝试一些文件选项,在本例中,我想计算在 ReadAllText 的帮助下创建的文本文件中有多少个单词,但是,路径名始终显示异常。

\n

这是我的代码:

\n
var path = @"\xe2\x80\xaa\xe2\x80\xaaC:\\Users\\pandrews\\countme.docx";\n\n            //Checks if file exists or not \n            if (File.Exists(path))\n            {\n                Console.WriteLine("File Exists");\n\n                var content = File.ReadAllText(path);\n\n                Console.WriteLine(content);\n\n            } else {\n\n                Console.WriteLine("File doesn't exist");\n\n            }\n            \n            //Checks if directory exists, if it does it returns a list of files in the directory and shows on the console.\n\n            if(Directory.Exists(@"C:\\Users\\pandrews"))\n            {\n                Console.WriteLine("Directory exists");\n\n                var files = Directory.GetFiles(@"C:\\Users\\pandrews");\n\n                foreach(var item in files)\n                {\n                    Console.WriteLine(item);\n                }\n\n            } else \n            {\n                Console.WriteLine("Directory doesn't Exist");\n            }\n
Run Code Online (Sandbox Code Playgroud)\n

正如你所看到的,我检查文件是否存在,但 Visual Studio 说不存在,但是,如果我检查目录是否存在,它会说存在,如果我检查文件列表,它会列出我想要读取的文件。

\n
C:\\Users\\pandrews\\.gitconfig\nC:\\Users\\pandrews\\countme.docx\nC:\\Users\\pandrews\\NTUSER.DAT\nC:\\Users\\pandrews\\ntuser.dat.LOG1\nC:\\Users\\pandrews\\ntuser.dat.LOG2\nC:\\Users\\pandrews\\ntuser.ini\n
Run Code Online (Sandbox Code Playgroud)\n

如果我使用 try catch,当尝试读取所有文本时,它会显示以下异常:

\n
El nombre de archivo, el nombre de directorio o la sintaxis de la etiqueta del volumen no son correctos. : 'C:\\Users\\pandrews\\source\\repos\\testingreadalltext\\testingreadalltext\\bin\\Debug\\netcoreapp3.1\\??C:\\Users\\pandrews\\countme.docx'\n
Run Code Online (Sandbox Code Playgroud)\n

翻译:文件名、目录名或卷标语法不正确。

\n

我在我的代码中看不到任何错误,但希望其他人能够看到。

\n

编辑:我想添加我以管理员身份登录,用户管理员是文件的所有者,并且我已以管理员身份执行了 Visual Studio。

\n

Ren*_*eno 5

汉斯的评论是正确的。

当您检查(使用浏览器工具)HTML 时,该字符在您的帖子中可见;在那里你看到特殊字符:“202A” 在此输入图像描述

另外,您可能希望使用特殊的环境文件夹常量,而不是硬编码用户文件夹的路径:例如

var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "countme.docx");
Run Code Online (Sandbox Code Playgroud)