string file = request.QueryString["file"];
try
{
// Open the file and display its contents, one line at a time.
response.Write("<b>Listing " + file + "</b><br>");
StreamReader r = File.OpenText(server.MapPath(Path.Combine("./", file)));
string line = "";
while (line != null)
{
line = r.ReadLine();
if (line != null)
{
// Make sure tags and other special characters are
// replaced by their corresponding HTML entities, so they
// can be displayed appropriately.
line = server.HtmlEncode(line);
// Replace spaces and tabs with non-breaking spaces
// to preserve whitespace.
line = line.Replace(" ", " ");
line = line.Replace("\t", " ");
// A more sophisticated source viewer might apply color-coding.
response.Write(line + "<br>");
}
}
r.Close();
}
catch (ApplicationException err)
{
response.Write(err.Message);
}
response.Write("</html></body>");
}
public bool IsReusable
{
get { return true; }
}
}
}
Этот код просто находит требуемый файл, читает его содержимое и использует небольшую замену строк (например, заменяет пробелы неразрываемыми пробелами и разрывы строк элементом <br/>) и шифрование HTML, чтобы создать представление, безопасно отображаемое в браузере. Более подробно об этих технологиях чтения и манипулирования файлами мы поговорим в главе 13.
предыдущая следующая страница оглавление
247