I have a folder which contains lots of files. I need to write C# code that will open and read and display the content of it. Is this efficient code or should something be changed?
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using System.Text;
using System.Collections;
class Program
{
static void Main()
{
var sw = Stopwatch.StartNew();
ProcessRead().Wait();
Console.Write("Done ");
Console.WriteLine("Elapsed Time" + sw.ElapsedMilliseconds+"and"+sw.ElapsedTicks);
Console.ReadKey();
}
static async Task ProcessRead()
{
string folder = @"Directory";
string[] fileEntries = Directory.GetFiles(folder);
int count = 0;
foreach (string fname in fileEntries)
{
if (File.Exists(fname) == false)
{
Console.WriteLine("file not found: " + fname);
}
else
{
try
{
count++;
string text = await ReadTextAsync(fname);
Console.WriteLine(text);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
Console.WriteLine(count);
}
static async Task<string> ReadTextAsync(string filePath)
{
using (FileStream sourceStream = new FileStream(filePath,
FileMode.Open, FileAccess.Read, FileShare.Read,
bufferSize: 4096, useAsync: true))
{
StringBuilder sb = new StringBuilder();
byte[] buffer = new byte[0x1000];
int numRead;
while ((numRead = await sourceStream.ReadAsync(buffer, 0, buffer.Length)) != 0)
{
string text = Encoding.UTF8.GetString(buffer, 0, numRead);
sb.Append(text);
}
return sb.ToString();
}
}
}