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

|
    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 Reader中打开该文件。谢谢     
已邀请:
要下载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();
}
    
您只能通过浏览器的加载项在浏览器中阅读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     
您的方法读取文件的原始内容。 Txt文件可以正确显示,因为它们的内容是纯文本,doc / rtf / pdf和其他格式,需要专门的控件才能正确显示它们。     

要回复问题请先登录注册