簡體   English   中英

如何以可讀格式和asp.net C#顯示多行文本框中的文件內容

[英]how to display the contents of file in multi-line textbox in readable format and in asp.net C#

我正在使用FileUpload Control上傳FileUpload.aspx頁面中的文件,現在我想在不同的頁面中顯示文件的內容,例如-filecontents.aspx。 為此我使用StreamReader,甚至以編碼格式(不是可讀格式)獲取內容。

如何以可讀格式獲取上傳文件的內容。

這是我的代碼:

public string ShowContent(string path)
    {
        string savePath = @"D:\CloudStorageSecurity\CloudStorageSecurity\CloudServer1\";
        string strInput = "";
        string GetStream = "";

        if (File.Exists(path))
        {
            StreamReader sr = new StreamReader(path, Encoding.Unicode);
            strInput = sr.ReadLine();
            while (strInput != null)
            {
                GetStream += strInput;
                strInput = sr.ReadLine();
            }
            sr.Close();
        }
        else
        {
            Response.Write("file does not exist!");
        }
        txtFileCOntents.Text = GetStream;
    }

考慮到path是有效路徑並指向可讀文件格式(txt,html,rtf ...):

public string ShowContent(string path)
    {
        var result = string.Empty;

        if (File.Exists(path))
        {
            using(var sr = new StreamReader(path, Encoding.UTF8))
            {
                 result = sr.ReadToEnd();
                 sr.Close();
            }
        }
        else
        {
            Response.Write("file does not exist!");
        }
        txtFileCOntents.Text = result ;
    }

當你有result ,你可以做任何事情。
如果你想逐行閱讀:

public string ShowContent(string path)
    {
        var result = string.Empty;
        var tmpLine = string.Empty;
        if (File.Exists(path))
        {
            using(var sr = new StreamReader(path, Encoding.UTF8))
            {
                 while((tmpLine = sr.ReadLine()) != null)
                 {
                     result += tmpLine + "\n\r";
                 }
            }
        }
        else
        {
            Response.Write("file does not exist!");
        }
        txtFileCOntents.Text = result ;
    }

這一切都取決於您嘗試“閱讀”的文件類型。

我在評論中看到你試圖解析docx格式。 您可以通過OpenXML獲取可讀內容。 我想這個鏈接可以幫助你開始。

https://code.msdn.microsoft.com/office/CSOpenXmlGetPlainText-554918c3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM