'File.Create is creating a directory and not a file

As a short summary, I have a string constant for a file location that includes the file name and extension such as @"C:\foldername\subfolder\filename.json. When calling File.Create from System.IO, it's creating a directory rather than the file maybe 5% of the time.

Does anyone have any insight as to what needs done different to prevent this?

if (File.Exists(fileName))
{
    return File.GetLastWriteTime(fileName);
} 
else
{
    try
    {
        File.Create(fileName).Close();
        return File.GetLastWriteTime(fileName);
    }
    catch (Exception ex)
    {
        Logging.sharedLogging.Log(SharedLogging.LoggingLevel.Error, "[CacheDirectoryLogic.GetOverridesLastWriteTime] Failed to create Override.json. Reason: " + ex.Message);
        return null;
    }
}

where fileName is @"C:\WD\Data\Cache\Override.json";



Solution 1:[1]

I think there should be some exception thrown, but your catch block will just log somewhere and ignore the error, so you may want to check your logger to see any exception mentioned. It will be helpful for us to understand the issue.

There are few possible root causes for the issue.

1. Permission issue

  • I notice the file path is in C drive. If the directory requires admin privilege to write files in the folder, it may throw access denied exception.
  • Tried to change the file path to D drive, which less likely has admin privilege restriction.

2. Directory is not fully created

  • Better practice for file creation with a full path -- check for directory existence before creating the file.
  • File.Create() does not create directory automatically. And it will throw error if directory is not found.
  • Code sample:
    var directory = @"C:\WD\Data\Cache\";
    var fileName = Path.Combine(directory, "Override.json");
    
    if (!Directory.Exists(directory))
    {
      Directory.CreateDirectory(directory);
    }
    
    if (File.Exists(fileName))
    ...
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TYJ