Mildred Shimz
Mildred Shimz

Reputation: 617

working with StreamReader and text files

I want to put a test loop on the button click event. When I click this button, it reads the contents of the text file, but I want it to pop up an error message showing “unable to read file”, if it’s not a text file.... This is my code

private void button3_Click(object sender, EventArgs e)
{
    StreamReader sr = new StreamReader(textBox1.Text);
    richTextBox1.Text = sr.ReadToEnd();
    sr.Close();
}

How can I go about it?

Upvotes: 0

Views: 11117

Answers (2)

Tom Pickles
Tom Pickles

Reputation: 900

Not the best code, but it should work. Ideally you would separate the logic into two methods, a function to check the file exists and is a text file (returning a bool), another to read the contents if the check function returned true and populate the textbox with the contents.

EDIT: This is better:

    private void button3_Click(object sender, EventArgs e)
    {
        string filePath = textBox1.Text;
        bool FileValid = ValidateFile(filePath);

        if (!IsFileValid)
        {
            MessageBox.Show(string.Format("File {0} does not exist or is not a text file", filePath));
        }
        else
        {
            textbox2.Text = GetFileContents(filePath);
        }
    }

    private bool IsFileValid(string filePath)
    {
        bool IsValid = true;

        if (!File.Exists(filePath))
        {
            IsValid = false;
        }
        else if (Path.GetExtension(filePath).ToLower() != ".txt")
        {
            IsValid = false;
        }

        return IsValid;
    }

    private string GetFileContents(string filePath)
    {
        string fileContent = string.Empty;

        using (StreamReader reader = new StreamReader(filePath))
        {
            fileContent = reader.ReadToEnd();
        }

        return fileContent;
    }

Upvotes: 1

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112259

A few if-statements and the namespace System.IO will do it

string filename = textBox1.Text;
if (Path.GetExtension(filename).ToLower()) == ".txt") {
    if (File.Exists(filename)) {
        // Process the file here
    } else {
        MessageBox.Show("The file does not exist");
    }
} else {
    MessageBox.Show("Not a text file");
}

Upvotes: 2

Related Questions