我目前正在尝试读取文件,修改内部的一些占位符,然后将文件写入输出流。作为aspx.net中的页面响应的输出流,我在那里使用了OutputStream.Write方法(文件最后是一个附件)。有没有更好的方法来写入读取和修改文本行并将它们写入输出流?
我原本:
using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
while (readBytes < fs.Length)
{
tmpReadBytes = fs.Read(bytes, 0, bytes.Length);
if (tmpReadBytes > 0)
{
readBytes += tmpReadBytes;
page.Response.OutputStream.Write(bytes, 0, tmpReadBytes);
}
}
}
想事以后在我想出了以下内容:
foreach(string line in File.ReadLines(filename))
{
string modifiedLine = line.Replace("#PlaceHolder#", "NewValue");
byte[] modifiedByteArray = System.Text.Encoding.UTF8.GetBytes(modifiedLine);
page.Response.OutputStream.Write(modifiedByteArray, 0, modifiedByteArray.length);
}
但它看起来低效尤其是与转换。所以我的问题是:有没有更好的方法来做到这一点?
注意文件本身并不是很大,它是一个大约3-4 KB大小的文本文件。
为什么你读取字节而不是文本,如果你有什么是文本? – Albireo
Response.WriteLine(modifiedLine);'? – Luaan
@Albireo最初的代码不是来自我(我接管了那个项目)。我猜这是因为当时他使用.Write为OutputStream,他不想转换读取的字节,因此使用FileStream .Read方法和读取字节,而不是文本) – Thomas