简体   繁体   中英

C# ReadAllText File Doesn't Exist

I am creating a very basic program to try out some File options, in this case I want to count how many words are in a text file I have created with the help of ReadAllText, however, the path name always shows an exception.

This is my code:

var path = @"‪‪C:\Users\pandrews\countme.docx";

            //Checks if file exists or not 
            if (File.Exists(path))
            {
                Console.WriteLine("File Exists");

                var content = File.ReadAllText(path);

                Console.WriteLine(content);

            } else {

                Console.WriteLine("File doesn't exist");

            }
            
            //Checks if directory exists, if it does it returns a list of files in the directory and shows on the console.

            if(Directory.Exists(@"C:\Users\pandrews"))
            {
                Console.WriteLine("Directory exists");

                var files = Directory.GetFiles(@"C:\Users\pandrews");

                foreach(var item in files)
                {
                    Console.WriteLine(item);
                }

            } else 
            {
                Console.WriteLine("Directory doesn't Exist");
            }

As you can see, I check if the file exists yet visual studio says it doesn't, however, if I check if the directory exists, it says it does and if I check the list of files it lists the file I want to read.

C:\Users\pandrews\.gitconfig
C:\Users\pandrews\countme.docx
C:\Users\pandrews\NTUSER.DAT
C:\Users\pandrews\ntuser.dat.LOG1
C:\Users\pandrews\ntuser.dat.LOG2
C:\Users\pandrews\ntuser.ini

If I use a try catch, when trying to read all text it shows the following exception:

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'

Translated: The name of the file, the name of the directory or the syntax of the volume label aren't correct.

I can't see any error in my code but hopefully someone else might be able to.

EDIT: I want to add I am signed in as an admin, the user admin is the owner of the file and i've executed Visual Studio as administrator.

Hans is correct in his comment.

The character is visible in your post when you inspect (with the browser tools) the HTML; there you see the special character:"202A" 在此处输入图片说明

Also, you might want to use the special environment folder constants instead of hard coding your path to your users folder: Eg

var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "countme.docx");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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