9

I added an alternative code-path using an input string rather than reading from a file. I would require an empty FileInfo object as I have many instances which access the Name, Length and Extension property.

Ideally I am looking for something like

FileInfo _fileinfo = new FileInfo(File.Empty);

However there is only one FileInfo constructor, which appears to require a valid file. Any solution to creating an empty-initialized FileInfo object, which does not require the creation of an empty dummy file?

Lorenz Lo Sauer
  • 23,698
  • 16
  • 85
  • 87
  • Well, that's not going to work. It is immutable, no default constructor and none of the properties have setters. Surely you can make do with your own class. – Hans Passant Sep 20 '12 at 18:57
  • 1
    `FileInfo` doesn't need a valid file per se - `new FileInfo("H:\\HelloWorld.txt");` will work without exception, however `.Exists` will obviously return false. – maxp Oct 07 '15 at 11:52

2 Answers2

5

I just came across a similar problem. What do you think about starting with:

FileInfo _fileinfo = null;

After that, you could just do:

_fileinfo = new FileInfo(<string of file with path>);

You would then have an object that you could pass as parameter to your methods. Don't foget to check if your object is null before you try to get the values for .Name and so on

if(null != _fileinfo)
{
  //some code
}
Zhatyr
  • 75
  • 1
  • 2
0

As pointed out in the comments, FileInfo will happily construct with non-existant paths, but they have to be valid path strings (which you call a 'valid file'). (See https://learn.microsoft.com/en-us/dotnet/api/system.io.fileinfo?view=net-5.0 for what is considered a valid path.)

The solution would be to simply write

FileInfo _fileinfo = new FileInfo(@"C:\NonExistant.txt");

instead of

FileInfo _fileinfo = new FileInfo(File.Empty);

You can then think of your own test to see if you're dealing with the 'Empty' FileInfo object, such as checking drive letter, extension, File.Exists tests and such.

Zimano
  • 1,870
  • 2
  • 23
  • 41