7

I have searched and only found this information for console, but I was wondering if it is possible to read text from a file on my local machine into the code, format it, and display in on screen? We have a text file with some legal jargon that can be updated periodically, and instead of having the user sift through code, we were wanting to just update the text file and have the changes apply online.

Thanks!

EDIT: Thanks to everyone's comments, here is an edit with the requirements. The program is in C# ASP.NET website. I have read many articles about this being done in a console, but I am not sure how to make it work for me. Thanks again for everybody's contribution.

4

2 回答 2

17

你有完整的程序(ASP.net)。App_Data您的 ASP.net 应用程序内的文件夹内必须有一个文件,在此应用程序中,您的文件名“Details.txt ”应该在您的App_Data文件夹内可用。

您的网页中有隐藏字段和可用段落。当表单加载时,此时从文本文件中读取数据并填充到隐藏字段控件。并在 $(document).ready()Jquery 函数中将数据从隐藏字段填充到段落。

您的.aspx页面:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="ReadFromTextFileToTextBoxWebApp._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
  <style type="text/css" >
   .details
   {
       background-color:Purple;color:yellow;top: 100px;
   }
   .txtDetails
   {
       left:150px;width:200px;height:100px;
   }
  </style>
  <script src="Scripts/jquery-1.8.3.min.js" type="text/javascript"></script>
  <script type="text/javascript" language="javascript">
      $(document).ready(function () {
          var data = $("#<%=HiddenField1.ClientID %>").val();
          $('#pTextData').text(data);
      });

</script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h2>
        Welcome to ASP.NET!
    </h2>
     <div>
        <asp:HiddenField ID="HiddenField1" runat="server" />
        <p id="pTextData">
        </p>
     </div>
</asp:Content>

这是您在页面后面的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace ReadFromTextFileToTextBoxWebApp
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var data = File.ReadAllText(Server.MapPath("~/App_Data/Details.txt"));
            HiddenField1.Value = data.ToString();   
        }           
    }
}
于 2013-10-28T18:31:27.430 回答
6

这是在.Net中工作的两种方法

var legal = File.ReadAllText(@"C:\Legal\Legalease.txt");

// Or from the CWD of where the program is executing

var legal = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "Legalease.txt"));

更新

请记住,Asp.Net 是作为在 IIS 的应用程序池中为该网站定义的用户运行的。如果用户对文件所在的位置没有读取权限,则无法读取该文件。确保网站应用程序池中定义的用户有权读取文件并验证文件已发布到读取位置。

于 2013-10-28T17:43:39.740 回答