Search code examples
c#filestream

Fastest way to convert File to Stream


I did google and see different ways to read and write a file but I need fastest way to convert file into a stream.

I am working on improving performance of a method which simply converts the file into stream. This will be called countless number of times daily and we are looking at improving it's performance. Please see below the method which I wrote.

public static Stream GetFileStream(string fileName)
{
   Stream result;
   try
   {
      if (File.Exists(fileName))
      {
          result = File.OpenRead(fileName);
          if (result.Length > 0)
          {
              result.Seek(0, SeekOrigin.Begin);
          }
      }
      else
      {
         throw new Exception(string.Format("{0} file not found.", fileName));
      }
   }
   catch (Exception ex)
   {
       throw ex;
   }
   return result;
}

The sample test calling code ( which I do not have control is like below)

List<string> fileNames = new List<string>();
//add almost 30,000 file names to string

List<Stream> fileStreams = new List<Stream>();
foreach(string fileName in fileNames)
{
   Stream fileStream = FileUtility.GetFileStream(fileName);
   fileStreams.Add(fileStream);
}

I am looking at how to improve performance of my method ConvertToStream.

Thanks in advance.

UPDATE 1

As per friends below, I converted my method like below

public static Stream ConvertToStream(string fileName)
{
   Stream result;
   try
   {
      result = File.OpenRead(fileName);        
   }
   catch (Exception ex)
   {
      throw ex;
   }
   return result;
}

I will let you know about performance.

UPDATE 2

I got reply from my callers saying that refactor code not break anything. We are looking to refactor code outside of this method. I feel this method is good. Thanks yaakov and everyone...


Solution

  • public static Stream GetFileStream(string fileName) => File.OpenRead(fileName);
    

    The rest of your code is largely redundant:

    • The outer try/catch rethrows the existing exception, though it destroys the stack trace in the process.
    • If the file doesn't exist, File.OpenRead will throw a FileNotFoundException already. You don't need to do this check yourself, and doing so allows room for a race condition anyway, if the file gets deleted between calls to File.Exists and File.OpenRead.
    • A newly opened file stream will start at the beginning of the file, so there is no need to Seek to the start.