将文件转换为流的最快方法

Zig*_*ler -2 c# filestream

我谷歌了一下,看到了读取和写入文件的不同方法,但我需要最快的方法将文件转换为流。

我正在努力提高一种简单地将文件转换为流的方法的性能。这每天都会被调用无数次,我们正在考虑改进它的性能。请看下面我写的方法。

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;
}
Run Code Online (Sandbox Code Playgroud)

示例测试调用代码(我无法控制,如下所示)

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);
}
Run Code Online (Sandbox Code Playgroud)

我正在研究如何提高我的方法 ConvertToStream 的性能。

提前致谢。

更新1

根据下面的朋友,我将我的方法转换如下

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

我会让你了解性能。

更新2

我收到来电者的回复说重构代码不会破坏任何东西。我们正在寻求重构此方法之外的代码。我感觉这个方法不错。谢谢雅科夫和大家...

yaa*_*kov 5

public static Stream GetFileStream(string fileName) => File.OpenRead(fileName);
Run Code Online (Sandbox Code Playgroud)

其余代码很大程度上是多余的:

  • 外部try/catch重新抛出现有异常,尽管它破坏了进程中的堆栈跟踪。
  • 如果文件不存在,File.OpenRead将抛出FileNotFoundExceptionalready。您不需要自己执行此检查,并且如果文件在调用 和 之间被删除,那么无论如何都会为竞争条件留出File.Exists空间File.OpenRead
  • 新打开的文件流将从文件的开头开始,因此不需要从头Seek开始。