我用Google做的,看到了读写文件的不同方法,但是我需要最快的方法将文件转换为流。
我正在努力提高一种将文件简单地转换为流的方法的性能。这将被称为每天无数次,我们正在寻求改善其性能。请看下面我写的方法。
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;
}
示例测试调用代码(我没有控制权,如下所示)
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);
}
我正在研究如何提高我的方法ConvertToStream的性能。
提前感谢。
public static Stream GetFileStream(string fileName) => File.OpenRead(fileName);
如上所述,文件操作是繁琐的操作,特别是当要读取的文件是大文件时。因此,使基础流程保持简单可能会帮助您解决问题。
using (Stream str = new StreamReader(fileName).BaseStream)
{
//do whatever you want here
}
或者您甚至可以在读取流之前添加文件是否存在检查以防止错误。
FileStream
constructor怎么了?
请注意,文件I / O永远不会“快速”。当然,您可以以更有效的方式执行操作,但是文件I / O通常是应用程序中较慢的部分之一。