开发者

Couldn't read files properly using asp.net C#

开发者 https://www.devze.com 2023-03-08 04:09 出处:网络
System.IO.StreamReader sr = new System.IO.StreamReader(Server.MapPath(strheadlinesid1)); string line; while (sr.Peek() != -1)
    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>");
    }

I'm using the above code to read a file .But this is only reading .txt files properly(Not reading .doc,docx and .rtf properly). And Can anybody tell how to read .pdf files in web browser like opening in a开发者_运维百科 adobe reader in a new tab.Thank you


To download a PDF file call this code with your pdf file: Depending on the user's settings for their browser, it may open in a new tab as you want.

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();
}


You can read the pdf file in the browser only by add-in for your browser, downloadable from here: http://kb2.adobe.com/cps/331/331025.html

For correct view the files in the browser you should set the mime types for it:

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

More about the Mime types: http://www.w3schools.com/media/media_mimeref.asp


Your approach reads the raw content of the file. Txt-Files display correctly because their content is plain text, doc/rtf/pdf and other formats will require specialized controls to display them properly.

0

精彩评论

暂无评论...
验证码 换一张
取 消