open file stream c# code example
Example 1: c# read file stream
using System;
using System.IO;
using System.Text;
namespace StreamReaderReadToEnd
{
class Program
{
static void Main(string[] args)
{
var path = @"C:\Users\Jano\Documents\thermopylae.txt";
using var fs = new FileStream(path, FileMode.Open, FileAccess.Read);
using var sr = new StreamReader(fs, Encoding.UTF8);
string content = sr.ReadToEnd();
Console.WriteLine(content);
}
}
}
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));
}
}
}
}
Example 3: c# read file stream
var fileText = File.ReadAllText(@"path\to\my\file.txt");
var fileLines = File.ReadAllLines(@"path\to\my\file.txt");