Skip to content

Instantly share code, notes, and snippets.

@relliv
Created May 8, 2018 08:44
Show Gist options
  • Select an option

  • Save relliv/8d9507740349eca245507d64846002e5 to your computer and use it in GitHub Desktop.

Select an option

Save relliv/8d9507740349eca245507d64846002e5 to your computer and use it in GitHub Desktop.
C# Create Text File And Write Content And Read Content
public void CreateFileaAndWrite()
{
// get path
string filepath = @"textfile.txt";
// open or create file
FileStream streamfile = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.Write);
// create stream writer
StreamWriter streamwrite = new StreamWriter(streamfile);
// add some lines
streamwrite.WriteLine("Forbidden speak in this line.");
streamwrite.WriteLine("Forbidden be quiet in this line.");
streamwrite.WriteLine("Sleeping in this line may only be possible by silence of the second line.");
streamwrite.WriteLine("Your custom text");
// clear streamwrite data
streamwrite.Flush();
// close stream writer
streamwrite.Close();
// close stream file
streamfile.Close();
}
public void ReadFile()
{
// get path
string filepath = @"textfile.txt";
// open file
FileStream streamfile = new FileStream(filepath, FileMode.Open, FileAccess.Read);
// create stream reader
StreamReader streamreader = new StreamReader(streamfile);
// reads to end of file
string content = streamreader.ReadToEnd();
// close stream reader
streamreader.Close();
// close stream file
streamfile.Close();
MessageBox.Show(content, "File Content:", MessageBoxButton.OK, MessageBoxImage.Information);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment