c# get file from file browser code example
Example 1: open file dialog c#
var fileContent = string.Empty;
var filePath = string.Empty;
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
filePath = openFileDialog.FileName;
var fileStream = openFileDialog.OpenFile();
using (StreamReader reader = new StreamReader(fileStream))
{
fileContent = reader.ReadToEnd();
}
}
}
MessageBox.Show(fileContent, "File Content at path: " + filePath, MessageBoxButtons.OK);
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));
}
}
}
}