473,837 Members | 1,524 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Write/Read A Text File - C#

319 Contributor
In this article: You will learn to Write or Read A Text File.

Let's Begin:
First Create a new project (ConsoleApp or WinApp).
And Make sure your program uses these namespaces:
Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.IO;
  3. using System.Diagnostics;
Now, we will begin writing text to a file:
1)- Create a new stream-writer and open the file:
Expand|Select|Wrap|Line Numbers
  1. TextWriter tw = new StreamWriter(@"C:\Hello.txt");
2)- Write text to the file:
Expand|Select|Wrap|Line Numbers
  1. tw.WriteLine("Hello");
3)- Close the file.
Expand|Select|Wrap|Line Numbers
  1. tw.Close();
4)- Launch the file:
Expand|Select|Wrap|Line Numbers
  1. Process.Start(@"C:\Hello.txt");
Here is all the code:
Expand|Select|Wrap|Line Numbers
  1. //Creating a new stream-writer and opening the file.
  2. TextWriter tsw = new StreamWriter(@"C:\Hello.txt");
  4. //Writing text to the file.
  5. tsw.WriteLine("Hello");
  7. //Close the file.
  8. tsw.Close();
  10. //Launch the file.
  11. Process.Start(@"C:\Hello.txt");
  13. Console.WriteLine("You're done, press any key to exit...");
  14. Console.ReadKey();

Now, we will begin reading text from a file:
1)- Creating a new stream-reader and opening the file:
Expand|Select|Wrap|Line Numbers
  1. TextReader trs = new StreamReader(@"C:\Hello.txt");
2)- Reading text of the file:
Expand|Select|Wrap|Line Numbers
  1. //Reading all the text of the file.
  2. Console.WriteLine(trs.ReadToEnd());
  4. //Or Can Reading a line of the text file.
  5. //Console.WriteLine(trs.ReadLine());
3)- Close the file:
Expand|Select|Wrap|Line Numbers
  1. trs.Close();
Here is all the code:
Expand|Select|Wrap|Line Numbers
  1. //Creating a new stream-reader and opening the file.
  2. TextReader trs = new StreamReader(@"C:\Hello.txt");
  4. //Reading all the text of the file.
  5. Console.WriteLine(trs.ReadToEnd());
  7. //Or Can Reading a line of the text file.
  8. //Console.WriteLine(trs.ReadLine());
  10. //Close the file.
  11. trs.Close();
  13. Console.WriteLine("Press any key to exit...");
  14. Console.ReadKey();
Hope this helped you.
Jul 6 '07 #1
6 249009
2 New Member
I think it 'll hlp me in project...
Feb 13 '08 #2
3 New Member
i need like this hw can i read and write the data into and from .mdb files ie MS ACCESS files.... using C#.. i need that if i enterd a text in a textbox it wil go and store into a .mdb file columns.. and hw can i retrive it back...
Feb 26 '08 #3
1 New Member
Expand|Select|Wrap|Line Numbers
  1. // remember that you name your class GetDataFromMDB and store it under this filename
  2. using System;
  3. using System.IO;
  4. using System.Data;
  5. using System.Data.OleDb;
  7. namespace OLE_DataGet  // Use your project-namespace here
  8. {
  9.     public class GetDataFromMDB
  10.     {
  11.         private DataTable mDataTable = new DataTable();
  13.         #region constructor 
  14.         /// <summary>
  15.         /// The constructor itself
  16.         /// </summary>
  17.         public GetDataFromMDB
  18.         {
  19.             // Anything you will do here, do it.
  20.         }
  21.         #endregion
  24.         #region MS Access (MDB) access
  25.         /// <summary>
  26.         /// Initialize and read a MDB (MS-Access-File)[here "MDB_FileName.MDB"] and 
  27.                 /// store 3 field [here TableItem1,TableItem2,TableItem3] out of the 
  28.                 /// database into a DataTable (mDataTable)
  29.         /// </summary>
  30.         /// <param name="pathToMDBfile">combined path and filename to the DataBaseFile</param>
  31.         /// <returns>true if success</returns>
  32.         private bool ReadDataBaseDBF(string pfad)
  33.         {
  34.             bool done = false;
  35.             string source = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + pathToMDBfile;
  36.             // select Table(MDB_FileName) und FieldNames(TableItem1,TableItem2,TableItem3)
  37.                         // to be read.
  38.                         // this is the SQL select message for the Jet-Engine to be used here
  39.             string select = "SELECT TableItem1, " + 
  40.                                                "TableItem2, " +
  41.                                "TableItem3 " +
  42.                            "FROM MDB_FileName";
  43.             try
  44.             {
  45.                 OleDbConnection conn = new OleDbConnection(source);
  46.                 conn.Open();
  47.                 OleDbCommand cmd = new OleDbCommand(select, conn);
  48.                 OleDbDataReader reader = cmd.ExecuteReader();
  49.                 // read TableItems to DataTable
  50.                 while(reader.Read())
  51.                 {
  52.                     this.mDataTable.Add(reader.GetString(0), 
  53.                                                             reader.GetString(1), 
  54.                                                             reader.GetString(2));
  55.                 }
  56.                 reader.Close();
  57.                 conn.Close();
  58.                 done = true;
  59.             }
  60.             catch (Exception e)
  61.             {
  62.                 // Whatever you will do with exception-handling, do it here
  63.             }
  64.             return done;
  65.         }
  66.         #endregion
  68.                 #region properties
  70.         /// <summary>
  71.         /// get your Datatable
  72.         /// </summary>                
  73.         /// <returns>the DataTable or null</returns>
  74.                 public DataTable MDB_DataTable
  75.                 {
  76.                    get
  77.                    {return mDataTable;}
  78.                 }
  79.                 #endregion
  80.     }
  81. }
Mar 5 '08 #4
Charles Cain
3 New Member
How can i ensure that i have received a file completely from an external source?Suppose i am receiving a file from an external source and i try to read the file before i have recieved the entire file.How can i ensure that the file has been received completely?
Jul 10 '08 #5
1 New Member
i need help regarding writting txt file data to access database because the file is of 200+MB size and the system is stuck when i open it.

plz help as soon as possible
Sep 9 '08 #6
1 New Member
i need help regarding writing txt file data to access database. the file size is 200+MB

plz reply as soon as possible

Hello dude! Are you going to transfer all the data from your database to a text file?

All data i mean!
Nov 6 '08 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

by: rishka | last post by:
Rishka Mar 17, 5:40 am show options Newsgroups: comp.databases.oracle.tools From: "Rishka" <ris...@webmail.co.za> - Find messages by this author Date: 17 Mar 2005 05:40:45 -0800 Local: Thurs, Mar 17 2005 5:40 am Subject: Read Text file into Oracle Reports Reply | Reply to Author | Forward | Print | Individual Message | Show original | Remove | Report Abuse
by: Mike John | last post by:
I want to write to text file, the follow text " My Name Is mike" Now, I have used the following sysntax: dim strFilePath as string = "C:\" dim strFileName as string = "MyFile.txt" fileopen(1,strfilepath & "\" & strfilename,output) write(1," My Name Is mike") fileclose(1)
by: Erich | last post by:
Hi, everybody! I would like my WebApp (ASP.NET) writes a text-file in my Web Host, so I could download it and import it to another application. Does anybody know how can I write a text file in my Web Host? My Web Host is HostBasket.
by: Erich | last post by:
Hi, everybody! I would like that my WebApp generates a text-file in my ISP, so I could download it and import it to another application. Does anybody know how can I write a text file running from an ISP? My ISP is HostBasket. Thanks in Advance!
by: Mika M | last post by:
Hi! I'm trying to read text file like... "Field1";"Field2";"Field3";"Field4" "ABCD";"EFGH";"1234";"20051020" "AABB";"CCDD";"2468";"20051021" "CCDD";"XXYY";"4321";"20051022" ....using OLE DB-provider. Unfortunately I can't affect in what kind of
by: broli85 | last post by:
I am writing an extension for Firefox 1.5. I would like to know if there is a way to write and read data to and from a file which is in the location of the extension (or somewhere in the user's harddisk, where I can store and retrieve some data). I tried to use a write function which I found in one of these threads and tried to give it "chrome://followmylink/files/" as the path. function fileWriter (filename,content) { try { var...
by: Wanjun Yu | last post by:
What is the class name for open/write/read a text file? I can't find it in the reference book. Thanks! WJ
by: abtet | last post by:
Hello people, I am new to php and have question on how to read text file and convert it to XML with php. . Can it be done if the text file contains text, image and also tables? please help and if anyone has the sources that could help solve my problem, please direct me to the source. Thank you very much -abtet-
by: neveen | last post by:
i want to open and read text file using j2me that can run on mobile 6630 then i want to make button called read that when pressed the data inside text display
by: karimkhan | last post by:
I am trying to read text file , here is the code , I cant use activex control so plz give me some way.... <html> <head> <script type="text/javascript"> function r() {
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.