open file in c# console application system.io code example
Example 1: c# open text file
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string path = @"c:\temp\MyTest.txt";
if (!File.Exists(path))
{
using (FileStream fs = File.Create(path))
{
Byte[] info =
new UTF8Encoding(true).GetBytes("This is some text in the file.");
fs.Write(info, 0, info.Length);
}
}
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
}
Example 2: opening a file in c#
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string path = "test.txt";
using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.None))
{
Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
fs.Write(info, 0, info.Length);
}
using (FileStream fs = File.Open(path, FileMode.Open))
{
byte[] b = new byte[1024];
UTF8Encoding temp = new UTF8Encoding(true);
while (fs.Read(b,0,b.Length) > 0)
{
Console.WriteLine(temp.GetString(b));
}
}
}
}