How to check if a file exists when it was no file extension? C#

2.3k views Asked by At

The file test has no extension and I need help to either move or rename this file to something with a extension

if(File.Exists(@"C:\\Users" + Environment.UserName + "\\Desktop\\test"))
{                                                                 /\
                                               this file has no file extension
}
3

There are 3 answers

1
Rahul Tripathi On

Try like this:

DirectoryInfo d = new DirectoryInfo("directory path");
FileInfo[] f = d.GetFiles("test.*");
if (f.Length > 0)
{
   File.Move(oldPath, newPath);
}
else
{
  //File does not exist
}

Also check Directory.GetFiles

0
Jegan On

Use the directory info to get the list of files in directory, then for those files without extension, remove them.

0
Martin On

I created a file named test with no extension in the folder M:\Incoming.

Running the following code works in both cases:

if (File.Exists(@"M:\Incoming\test"))
    Console.WriteLine("Exists");

if (File.Exists(@"M:\\Incoming\\test"))
    Console.WriteLine("Exists");

When using @ you do not need to specify two slashes, although it makes no difference anyway in this example.

Output:

Exists

Exists

Your problem is most likely to be in the way in which you are concatenating the strings.