无法使用asp.net C#正确读取文件

时间:2011-05-24 08:43:05

标签: c# asp.net pdf filereader

    System.IO.StreamReader sr = new System.IO.StreamReader(Server.MapPath(strheadlinesid1));

    string line;

    while (sr.Peek() != -1)
    {
        line = sr.ReadLine();
        Response.Write("<tr>"+"<td>"+ Server.HtmlEncode(line) + "</td>"+"</tr>");
    }

我正在使用上面的代码来读取文件。但这只是正确读取.txt文件(不正确地读取.doc,docx和.rtf)。任何人都可以告诉你如何在网页浏览器中阅读.pdf文件,比如在新标签页中打开adobe阅读器。谢谢

3 个答案:

答案 0 :(得分:2)

要下载PDF文件,请使用您的pdf文件调用此代码:根据用户的浏览器设置,可以根据需要在新选项卡中打开。

public static void DownloadFile(string fname, bool forceDownload)
{
    string path = fname;
    if (fname.StartsWith("~"))
        path = Server.MapPath(fname);
    string name = Path.GetFileName(path);
    string ext = Path.GetExtension(path);
    string type = "";
    // set known types based on file extension  
    if (ext != null)
    {
        switch (ext.ToLower())
        {
            case ".htm":
            case ".html":
                type = "text/HTML";
                break;

            case ".txt":
                type = "text/plain";
                break;

            case ".pdf":
                type = "Application/pdf";
                break;

            case ".doc":
            case ".rtf":
                type = "Application/msword";
                break;

            case ".exe":
                type = "application/octet-stream";
                break;

            case ".zip":
                type = "application/zip";
                break;
        }
    }
    if (forceDownload)
    {
        Response.AppendHeader("content-disposition",
            "attachment; filename=" + name);
    }
    if (!string.IsNullOrEmpty(type))
        Response.ContentType = type;
    Response.WriteFile(path);
    Response.End();
}

答案 1 :(得分:1)

您只能通过浏览器的加载项在浏览器中阅读pdf文件,可从此处下载: http://kb2.adobe.com/cps/331/331025.html

要正确查看浏览器中的文件,您应该为其设置mime类型:

context.Response.ContentType = "application/pdf";
context.Response.AppendHeader("Content-Disposition", "attachment; filename = " + fileName);

有关Mime类型的更多信息: http://www.w3schools.com/media/media_mimeref.asp

答案 2 :(得分:0)

您的方法会读取文件的原始内容。 Txt-Files显示正确,因为它们的内容是纯文本,doc / rtf / pdf和其他格式需要专门的控件来正确显示它们。