Write/Read A Text File - C#

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Atran
    Contributor
    • May 2007
    • 319

    #1

    Write/Read A Text File - C#

    Hello:
    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:
    Code:
    using System;
    using System.IO;
    using System.Diagnostics;
    Now, we will begin writing text to a file:
    1)- Create a new stream-writer and open the file:
    Code:
    TextWriter tw = new StreamWriter(@"C:\Hello.txt");
    2)- Write text to the file:
    Code:
    tw.WriteLine("Hello");
    3)- Close the file.
    Code:
    tw.Close();
    4)- Launch the file:
    Code:
    Process.Start(@"C:\Hello.txt");
    Here is all the code:
    Code:
    //Creating a new stream-writer and opening the file.
    TextWriter tsw = new StreamWriter(@"C:\Hello.txt");
    
    //Writing text to the file.
    tsw.WriteLine("Hello");
    
    //Close the file.
    tsw.Close();
    
    //Launch the file.
    Process.Start(@"C:\Hello.txt");
    
    Console.WriteLine("You're done, press any key to exit...");
    Console.ReadKey();

    Now, we will begin reading text from a file:
    1)- Creating a new stream-reader and opening the file:
    Code:
    TextReader trs = new StreamReader(@"C:\Hello.txt");
    2)- Reading text of the file:
    Code:
    //Reading all the text of the file.
    Console.WriteLine(trs.ReadToEnd());
    
    //Or Can Reading a line of the text file.
    //Console.WriteLine(trs.ReadLine());
    3)- Close the file:
    Code:
    trs.Close();
    Here is all the code:
    Code:
    //Creating a new stream-reader and opening the file.
    TextReader trs = new StreamReader(@"C:\Hello.txt");
    
    //Reading all the text of the file.
    Console.WriteLine(trs.ReadToEnd());
    
    //Or Can Reading a line of the text file.
    //Console.WriteLine(trs.ReadLine());
    
    //Close the file.
    trs.Close();
    
    Console.WriteLine("Press any key to exit...");
    Console.ReadKey();
    Hope this helped you.
  • Rii
    New Member
    • Feb 2008
    • 2

    #2
    I think it 'll hlp me in project...
    Thanks

    Comment

    • prabur
      New Member
      • Feb 2008
      • 3

      #3
      hi
      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...

      Comment

      • lissi
        New Member
        • Mar 2008
        • 1

        #4
        Code:
        // remember that you name your class GetDataFromMDB and store it under this filename
        using System;
        using System.IO;
        using System.Data;
        using System.Data.OleDb;
        
        namespace OLE_DataGet  // Use your project-namespace here
        {
        	public class GetDataFromMDB
        	{
        		private DataTable mDataTable = new DataTable();
        
        		#region constructor 
        		/// <summary>
        		/// The constructor itself
        		/// </summary>
        		public GetDataFromMDB
        		{
        			// Anything you will do here, do it.
        		}
        		#endregion
        
        
        		#region MS Access (MDB) access
        		/// <summary>
        		/// Initialize and read a MDB (MS-Access-File)[here "MDB_FileName.MDB"] and 
                        /// store 3 field [here TableItem1,TableItem2,TableItem3] out of the 
                        /// database into a DataTable (mDataTable)
        		/// </summary>
        		/// <param name="pathToMDBfile">combined path and filename to the DataBaseFile</param>
        		/// <returns>true if success</returns>
        		private bool ReadDataBaseDBF(string pfad)
        		{
        			bool done = false;
        			string source = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + pathToMDBfile;
        			// select Table(MDB_FileName) und FieldNames(TableItem1,TableItem2,TableItem3)
                                // to be read.
                                // this is the SQL select message for the Jet-Engine to be used here
        			string select = "SELECT TableItem1, " + 
                                                       "TableItem2, " +
        				               "TableItem3 " +
        					       "FROM MDB_FileName";
        			try
        			{
        				OleDbConnection conn = new OleDbConnection(source);
        				conn.Open();
        				OleDbCommand cmd = new OleDbCommand(select, conn);
        				OleDbDataReader reader = cmd.ExecuteReader();
        				// read TableItems to DataTable
        				while(reader.Read())
        				{
        					this.mDataTable.Add(reader.GetString(0), 
                                                                    reader.GetString(1), 
                                                                    reader.GetString(2));
        				}
        				reader.Close();
        				conn.Close();
        				done = true;
        			}
        			catch (Exception e)
        			{
        				// Whatever you will do with exception-handling, do it here
        			}
        			return done;
        		}
        		#endregion
        
                        #region properties
        
        		/// <summary>
        		/// get your Datatable
        		/// </summary>                
        		/// <returns>the DataTable or null</returns>
                        public DataTable MDB_DataTable
                        {
                           get
                           {return mDataTable;}
                        }
                        #endregion
        	}
        }

        Comment

        • Charles Cain
          New Member
          • Jul 2008
          • 3

          #5
          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?

          Comment

          • misbahiqbal
            New Member
            • Sep 2008
            • 1

            #6
            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

            Comment

            • kazuyabo
              New Member
              • Nov 2008
              • 1

              #7
              Originally posted by misbahiqbal
              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!

              Comment

              Working...