Various method to write file in C#
1- BufferedStream
- public void UsingBufferedStream()
- {
- using (var file = File.Create(@"D:\MyTempFolder\temp1.txt"))
- {
- using (var b = new BufferedStream(file))
- {
- using (var writer = new StreamWriter(b))
- {
- writer.WriteLine("Hello Hamid.");
- }
- }
- }
- }
2 - MemoryStream
- public void UsingMemoryStream()
- {
- using (var memory = new MemoryStream())
- {
- using (var writer = new StreamWriter(memory))
- {
- writer.WriteLine("Hello Hamid");
- writer.Flush();
- using (var fileStream = File.Create(@"D:\MyTempFolder\temp2.txt "))
- {
- memory.WriteTo(fileStream);
- }
- }
- }
- }
- public void UsingFile()
- {
- string s=”Hello Hamid”;
- File.WriteAllText(@"D:\MyTempFolder\temp3.txt ", s);
- }
- public static void UsingStreamWriter()
- {
- using (var writer = File.CreateText(@"D:\MyTempFolder\temp4.txt "))
- {
- writer.WriteLine("Hello Hamid");
- }
- }
- private void UsingFileStream()
- {
- using (var target = File.Create(@"D:\MyTempFolder\temp5.txt "))
- {
- using (var writer = new StreamWriter(target))
- {
- writer.WriteLine("Hello Hamid ");
- }
- }
- }
Call all the method in your place :
- class Program
- {
- static void Main(string[] args)
- {
- string path = @"D:\MyTempFolder";
- FileHandler.CreateDirectory(path);
- FileHandler.UsingBufferedStream();
- FileHandler.UsingFile();
- FileHandler.UsingMemoryStream();
- FileHandler.UsingStreamWriter();
- FileHandler.UsingWithFileStream();
- Console.WriteLine("File created in all ways at path :"+ path);
- Console.ReadKey();
- }
- }
- public static void CreateDirectory(string path)
- {
- try
- {
- if (!Directory.Exists(path))
- {
- DirectoryInfo di = Directory.CreateDirectory(path);
- }
- }
- catch (IOException ioex)
- {
- Console.WriteLine(ioex.Message);
- }
- }
I hope it will help for our C# family developer .
No comments:
Post a Comment