我目前正在尝试读取一个文件,修改其中的几个占位符,然后将文件写入输出流。作为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大小的文本文件。
发布于 2015-12-17 12:56:44
你不需要处理你自己的字节。
如果你知道这个文件现在和将来都很小,
this.Response.Write(File.ReadAllText("path").Replace("old", "new"));否则
using (var stream = new FileStream("path", FileMode.Open))
{
using (var streamReader = new StreamReader(stream))
{
while (streamReader.Peek() != -1)
{
this.Response.Write(streamReader.ReadLine().Replace("old", "new"));
}
}
}发布于 2015-12-17 13:01:04
要获取字符串数组中的行,请执行以下操作:
string[] lines = File.ReadAllLines(file);若要更改行,请使用循环。
for (int i = 0; i < lines.Length; i++)
{
lines[i] = lines[i].Replace("#PlaceHolder#", "NewValue");
}为了保存新文本,首先创建一个包含所有行的字符串。
string output = "";
foreach(string line in lines)
{
output+="\n"+line;
}然后将字符串保存到文件中。
File.WriteAllText(文件输出);
https://stackoverflow.com/questions/34334933
复制相似问题