I'm using the following C# code to read a tiny text file over a network share:
string fileContent;
using (var stream = File.OpenRead(filePath))
using (var reader = new StreamReader(stream, FileEncoding))
{
fileContent = await reader.ReadToEndAsync();
}
Even though the text file is very small (less than 10 KB) this operation sometimes takes ~7 seconds to run. When that happens, I've noticed most of the time is spent on
File.OpenRead(filePath)
This is probably due to Windows having to resolve the file share and to acquire locks on the file over the network. As that method call is not asynchronous, this is blocking my current thread for several seconds.
Is there a safe way to read a file from disk asynchronously that also performs OpenRead asynchronously?