I remember coding file access using the Win API about 15 years ago. It was much faster than using the FileStream of my language at the time (Delphi).
I spent a while today experimenting in C# under .Net 4.5, and I cannot see a real advantage to using the Win API. Most of the time the standard FileStream is faster, even with its buffering behavior (I know that used to add a substantial overhead a decade ago).
I’ve studied this research article by Microsoft, but it’s over 10 years old now and not very applicable.
So my question is this: when is it advantageous to use the Win API as opposed to the standard FileStream?
7
When using .NET (particularly recent versions of .NET), a good guideline is to always use the built-in .NET functionality until and unless there is a marked benefit to doing otherwise. In other words: assume .NET is the right way to get the job done until you strongly suspect (or know) that it isn’t. Nine times out of ten, the Framework (having been used so widely) will take into account checks and performance improvements that you won’t consider.
It’s really the same reason people say not to roll your own security solution if you can avoid it – because it’s already been done by someone who is probably smarter than you and knows more about it, and other people have already tested it. The same applies to a widespread library like .NET. If someone has already done the work for you, and that work has been vetted by thousands or millions of users, why not go with that until you have a reason not to (such as it not providing the functionality or speeds you need).
6
Using Win API, you can support long paths in your application:
[PathTooLongException]: The specified path, file name, or both are too
long. The fully qualified file name must be less than 260 characters,
and the directory name must be less than 248 characters.
For more information about using long paths in .NET applications, see this blog series:
Link
0
In the general case you can basically assume they got it right. Thus, the only cases where you can reasonably hope to improve upon the library answer is when you’re doing something that’s generating inefficiency.
Personally, I have seen only one case: I had a file consisting of millions of integers that had to be read in and also updated in place, as well as a matching file of GUIDs where chunks would be read.