I am sorry for the weird title. I am working on a WPF app where I am supposed to load a text file from the system by clicking a button and read the contents of the file and display the content of textfile in a textbox.
I have done the following:
XAMl:
<TextBox Grid.Column="2" Text="{Binding Path=WriteMessage, Mode=TwoWay}" Name="MessageWrite" />
<Button Content="Load" Command="{Binding Path=LoadFileCommand}" Name="button8" />
ViewModel Class:
// Method gets called when LOAD Button is Clicked
private void ExecuteLoadFileDialog()
{
FileReader mFile = new FileReader(); // Its a Class Which Reads The File
var dialog = new OpenFileDialog { InitialDirectory = _defaultPath };
dialog.ShowDialog();
dialog.DefaultExt = ".txt";
dialog.Filter = "Text Files(*.txt)|*.txt|All(*.*)|*";
string path;
path = dialog.FileName;
using (StreamReader sr = new StreamReader(path))
{
WriteMessage = sr.ReadToEnd();
}
}
File Reader Class:
class FileReader : I2CViewModel.IFileReader
{
public string Read(string filePath)
{
byte[] fileBytes = File.ReadAllBytes(filePath);
StringBuilder sb = new StringBuilder();
foreach (byte b in fileBytes)
{
sb.Append(Convert.ToString(b, 2).PadLeft(8, '0'));
}
return sb.ToString();
}
}
The problem I am facing here is, when I click the load Button, it opens a filedialog but it displays all the files rather than just displaying .Txt Files. How to make sure only .txt files are visible?
Secondly when I click the button, the dialog pops up and if i click cancel button, the application crashes showing "Empty path name is not legal." which is pointing to using (StreamReader sr = new StreamReader(path))
How can I clear these issues?? :)