Question

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?? :)

Was it helpful?

Solution

Two quick things:

You are setting the filter AFTER showing the dialog thus rendering the filter useless

You should wrap the using block on an if to see if the user canceled the operation (dialog's FileName property stays empty) and wrap the readToEnd call on a try - catch block just in case

Those are my quick 2 cents

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top