C# vs. Java: Creating and Checking Existence of a File

Although C# and Java are very similar languages, there are many tricky differences. For example, consider this Java code:

DateFormat timeFormat = new SimpleDateFormat("yyMMdd_HHmmss");
String timeString = timeFormat.format(new Date());
File f = new File(timeString + "test.txt");
if (f.exists() == true)
  System.out.println("The file already exists");
  System.out.println("I will create a new file");

The intent is to create a log file that has a unique time stamped-name. The assumption is that there are different process creating files. The Java “new File” statement creates an object in memory but doesn’t actually create a file on disk. So this code is OK.


But now consider this similar C# code:

DateTime now = DateTime.Now;
DateTime utcNow = now.ToUniversalTime();
string timeString = utcNow.ToString("yyMMdd_HHmmss");


FileStream f = File.Create(timeString + "test.txt");
if (File.Exists(timeString + "test.txt"))
  Console.WriteLine("The file already exists");
  Console.WriteLine("I will create a new file");

The C# “File.Create” statement actually writes an empty file to disk, so the file will always exist and no new file would ever be created.


Some Java code I was porting to C# looked something like this:

while (true)
  new file
  if file exists then
    sleep 1 second
    create file
    break out of loop
end while

Except for the fact that there’s no guarantee this loop would ever terminate (if multiple processes were somehow synched to create files every second), the code is OK. But the same approach in C# would definitely lead to an infinite loop. I know this for a painful fact.

This entry was posted in Miscellaneous. Bookmark the permalink.

One Response to C# vs. Java: Creating and Checking Existence of a File

  1. The analogue to Java’s `File` class, is `FileInfo` on .Net. It works the same way (with a path ctor and an explicit create method).

Comments are closed.