Reading and writing files in C#.net

Reading and writing files in C#.net


//author Gautam Chakrabarty
// date 12-05- 2008



//Code snippet to read the textfile(gautam.txt)




string filename="gautam.txt";
StreamReader myReader = new StreamReader(filename);
StringBuilder strBuilder = new StringBuilder();
string str = myReader.ReadLine();
while( str != null )
{
strBuilder.Append(str + "\n");
str = myReader.ReadLine();
}
myReader.Close();
txtMyTextBox.Text = strBuilder.ToString();



//Code snippet to write the data from textbox(txtMyTextBox) to textfile(gautam.txt).For this we have to change the property txtMyTextBox.ReadOnly to false


string filename="gautam.txt";
StreamWriter myWriter = new StreamWriter(filename, false);
myWriter.WriteLine(txtMyTextBox.Text);
myWriter.Close();


Comments

Author: Phagu Mahato31 Jan 2014 Member Level: Gold   Points : 8

Example code for writing files in c Sharp


using System;
using System.IO;

namespace writeapp
{
class TextFileWriter
{
static void Main(stxtreading[] args)
{
Textxtwriteriter txtxtwriterite = new StxtreadeamWriter("Exampletest.txt");
txtwrite.WriteLine(DateTime.Now);
txtwrite.Close();
}
}
}

Reading From a Text File.



using System;
using System.IO;

namespace csharp_station.howto
{
class TextFileReader
{
static void Main(stxtreading[] args)
{

Textreader txtread = new StxtreadeamReader("Exampletest.txt");

Console.WriteLine(txtread.ReadLine());

txtxtreadead.Close();
}
}

Example of Reading and writing files in c Sharp.

using System;
using System.IO;

namespace FileHandlingReadandwrite
{
class Program
{
static void Main(stxtreading[] args)
{
if(File.Exists("Exampletest.txt"))
{
stxtreading Mycontent = File.ReadAllText("Exampletest.txt");
Console.WriteLine("Your Current content of file:");
Console.WriteLine(Mycontent);
}
Console.WriteLine("Enter content for the file:");
stxtreading newContent = Console.ReadLine();
File.WriteAllText("Exampletest.txt", newContent);
}
}
}
// code for append content
File.AppendAllText("Exampletest.txt", newContent);



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: