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.

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
Peter
  • 427
  • 4
  • 9
  • 37
  • What have you tried? What are you having trouble with? Are you asking how to read a file? How to manipulate a string? How to use a `TextBox`? – SLaks Oct 28 '13 at 16:53
  • 1
    Did you see the very first result for https://www.google.com/search?q=C%23+read+file? – SLaks Oct 28 '13 at 16:54
  • Thanks for the links. I am wondering if this is only for a console or can this be done in .NET as well? It does not seem to work when I run in in my code. – Peter Oct 28 '13 at 16:59
  • `System.IO.File` can be used from any kind of .NET project. – mbeckish Oct 28 '13 at 17:31
  • 1
    This can absolutely be done, but your requirements here are too vague. For instance, a console app can be written in .NET. Do you mean an ASP.NET web site? If so, the trick is just to have some code-behind file in your site doing the same work the console code you've seen does, and instead of writing the contents to the console window you write the content to the page being rendered using some sort of control (like a label or textbox). – DaveD Oct 28 '13 at 17:33
  • For this exercise, there is no difference between ASP.NET and C#.NET other than the presentation (UI). All the code that does the "real work" is the same. – StingyJack Oct 28 '13 at 18:12

2 Answers2

17

You have the complete program (ASP.net). You must have a file inside the App_Data folder inside your ASP.net app, In this App your file name "Details.txt" which should be available inside your App_Data folder.

You have Hidden-field and a paragraph available in your web page. When form loads, at that moment read the data from the text file and populate to the Hidden-field control. And in $(document).ready() Jquery function populate data to paragraph from Hidden-field.

Your .aspx page :

<%@ 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>

and here is your code behind page :

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();   
        }           
    }
}
Chandan Kumar
  • 4,570
  • 4
  • 42
  • 62
  • Great! Last question. Is it possible to format it? It will likely just need to be in paragraphs, but what is the best way to style the text that is read in? – Peter Oct 28 '13 at 18:55
  • yes Peter, like here i m displaying in textbox . same you can do with other controls. See, if you are asking me which is the best control to display data(if your data readonly - means you are not going to edit the data) then better to use label control.add a css class and set style for that label control. if you got your answer, please mark this as answered by ticking it . – Chandan Kumar Oct 28 '13 at 19:28
  • Thank you, but how do I format the text into paragraphs? – Peter Oct 28 '13 at 19:30
  • I was just thinking that to tell you. See, if you want to edit data then better use textbox with beautiful css looks, Why i m telling u to use server controls because you have more benefits in server controls compare to simple static html controls. you can apply javascript as well as server side code for server controls , Server side code like data to be stored in db/xml or provide to a webservice...etc...etc.Still if you want data to be in html paragraph

    then you can make a ajax GET call when form loads and bind the data to your paragraph.

    – Chandan Kumar Oct 28 '13 at 19:38
  • please look another solution done by me using jquery and Hiddenfield Control to populate data to a paragraph. – Chandan Kumar Oct 30 '13 at 03:21
  • Great Answer, really helped, I got a couple of things from this also, such as the '~' to let the program auto plan the route to the directory – Alex Apr 12 '15 at 01:42
  • 1
    @Alex Nice to here it helped you. – Chandan Kumar Apr 13 '15 at 05:13
6

Here are two methods to work in .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"));

Update

Remember the Asp.Net is running as a user defined in IIS's application pool for that website. If the user does not have read access to where the file exists, it cannot be read. Make sure the user defined in the website's application pool has the right to read the file and verify the file has been published to the read location.

Community
  • 1
  • 1
ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
  • Thanks! I have the legal.txt file in my project folder in Visual Studio, but when I change the file name, it still gives me a error saying "Could not find file 'C:\Windows\SysWOW64\inetsrv\legal.txt'" whether I use the top method or the bottom method. – Peter Oct 28 '13 at 18:03
  • @Peter You say the file is in your project, but how is it being copied to the inetsrv directory? Also does the asp.net process have the permission to read from the inetsrv directory? I recommend you include the legal.txt file with the website and read it locally. Don't forget to change the file property in the project of `Copy to Output Directory` to `Copy if Newer` – ΩmegaMan Oct 28 '13 at 18:09
  • StreamReader is another way that is pretty fast too. – StingyJack Oct 28 '13 at 18:12
  • @StingyJack Nothing wrong with StreamReader, it gives one more control of the operation. Provide an example to the OP. :-) – ΩmegaMan Oct 28 '13 at 18:14
  • @StingyJack It's quite rare to actually need a `StreamReader` that is manually manipulated. `ReadLines` is virtually always sufficient, and is much easier to use. – Servy Oct 28 '13 at 18:17
  • Yes please! Thank you all! I know it is fairly simple. Text file in solution, code reads it, then displays it. But for some reason I am having these issues. Thanks again! – Peter Oct 28 '13 at 18:17
  • @Peter try different locations of the file and see if one can be read. Hand publish the file to the website and others. Remember, the process has to have read access to the target folder. – ΩmegaMan Oct 28 '13 at 18:20
  • ReadAll* seems to chews up a lot of resources, as it appears to load the file into the buffer entirely, where StreamReader and ReadLines (new to me, hadn't seen that one yet) appear to not. If you have a large legal document, you may have a problem loading the entire thing in memory. http://stackoverflow.com/questions/8037070/whats-the-fastest-way-to-read-a-text-file-line-by-line – StingyJack Oct 28 '13 at 19:22