Read File in String

Example of reading a file into a string.
Because the streamreader inherits from TextReader which implements the iDisposable interface we must use it with the using statement. Like this there are no open or garbaged files on a error:

    public class Files
    {

        public string ReadFile(string file)
        {
            string text = string.Empty;
            try{
                using (StreamReader streamreader = new StreamReader(file))
                {
                    text = streamreader.ReadToEnd();
                }
            }
            catch(Exception)
            {
                text="Error reading file";
            }
            return text;
        }
    }

With the new framework this can be done asynchronous with async and await:

        public async void ReadFileAsync(string file)
        {
            try
            {
                using (StreamReader streamreader = new StreamReader(file))
                {
                    Text = await streamreader.ReadToEndAsync();
                }
            }
            catch (Exception)
            {
                Text = "Error reader file";
            }
        }

{{opmerking.Naam}}:

{{opmerking.OpmerkingText}}

            

Saving your comment....

Naam is verplicht!
Email is verplicht!
Opmerking is verplicht!