Click here to Skip to main content
15,915,509 members
Please Sign up or sign in to vote.
3.67/5 (2 votes)
See more:
Hi all.

I am using Windows 8 and running Visual Studio 2013. I wanted to test if a file exists in a folder called "temp" in the "C" drive The file I called "test.txt": Below is the code:

C#
static void Main(string[] args)
        {

            string testFile = @"C:\temp\test.txt";

            if (File.Exists(testFile))
            {
                Console.WriteLine("Eureka. File found");

                Console.ReadLine();
            }
            else
            {
                Console.WriteLine("File is not found..");
                Console.ReadLine();
            }
        }


But, despite that this file exists (I am staring at it in the folder called temp in drive C!!), It keeps on jumping to the else statement. Please assist for I am losing my mind over this seemingly easy code.
Posted
Comments
Rahul VB 27-Jan-14 2:09am    
Very good question. Many developers make this mistake and great answer posted by OG.

1 solution

The code looks like it should work: and indeed if I check it here it does.
So...check your file. Open Windows Explorer, all look at the folder "C:\temp".
Right click the file and select Properties: (this should work in Win8, but I can't check)
Select the "Details" tab and look at the Name: is it "test.txt"? Or "test.txt.txt"?

Remember that Explorer hides the extensions for known files by default, so if you can see the ".txt" extension, it probably isn't the actual file extension - your code must refer to the exact file name, because it does not work with "hidden" extensions.
 
Share this answer
 
Comments
Wamuti 26-Jan-14 4:21am    
Ohhhh... It is text.txt.txt!! Thanks a million.
OriginalGriff 26-Jan-14 4:28am    
You're welcome!
Rahul VB 27-Jan-14 2:07am    
"MOM" award is your OG i swear it.
OriginalGriff 19-Apr-16 10:33am    
Do what?
Of course you can read files straight away with C#!
There are eight or more classes specifically to do just that!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900